JavaScript feature detection
In my Vanilla JS Pocket Guide on browser compatibility, I mention a technique called “cutting the mustard,” in which you make sure the most modern functions you’re using are supported before running your code.
var supports = 'querySelector' in document && 'addEventListener' in window;
if ( supports ) {
// Codes goes here...
}
// or...
if ( !supports ) return;
Features.js is a super lightweight feature detection library. It’s a bit like Modernizr, but with less frills.
You can include the whole thing in your project, but I actually think it’s more interesting to dig into the Feature.js source code and just grab the features you want to test.
For example, if I wanted to test for Service Worker support, I would do this:
if ( 'serviceWorker' in navigator ) {
// Run my scripts...
}
Check out Feature.js. It looks awesome!