Skip to main content Accessibility Feedback

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!


❄️ Black Friday Sale! Make 2018 the year you master JavaScript. From now through Monday, save up to 50% on my top JavaScript learning resources.

Have any questions or comments about this post? Email me at chris@gomakethings.com or contact me on Twitter at @ChrisFerdinandi.

Get Daily Developer Tips