With the following lines of code, browsers are categorized as being either “HTML4” or “HTML5” capable.
If a browser supports
querySelector, if it supports
localStorage, and if it also understands
The combination of feature detections in the code example above covers the majority of browsers released in the last six or so years. Oh, and Internet Explorer 9 (released in 2011) and newer. It’s possible this combination will work for you, but you’ll want to gather some analytics on this before making any decisions.
In the three years since the original mustard cut, browsers have progressed at a fantastic clip. Most significantly, in March of this year, Microsoft retired Internet Explorer in favor of the more-frequently updated Edge. With global usage of all versions of Internet Explorer prior to 11 sitting comfortably around 3% and the rapid adoption of current versions of other major browsers, it seems the time is right to spice up our mustard.
(I promise that’s the last food pun…)
if (!(‘visibilityState’ in document)) return;
A nice way to prevent your JS running in IE<10 and Android WebKit http://caniuse.com/#feat=pagevisibility
Much shorter, a touch more obscure, and only slightly more exclusive than the BBC News team’s original technique.
You may find, while evaluating your website’s usage statistics, that you want to raise the bar just a little bit higher. In that case, you may consider using
According to Can I use…,
devicePixelRatio is well-supported and first appeared in Internet Explorer in version 11. For testing and verification purposes, I put together this quick demo on CodePen. It’s nice and short and works as you’d imagine. Since we can use pixel density in HTML on an
<img> with the
srcset attribute and in CSS with resolution media queries, using the
devicePixelRatio feature detection may be a little more obvious to you and your teammates.
Your Mileage May Vary
I suggested earlier in this post that you look at your website’s analytics. I can’t stress this enough. The techniques outlined above are useful, but may not be the most appropriate choice for your website. Dive into the data you have at your disposal and make the best choice for your particular use case.