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!


🚀 I just relaunched my Vanilla JS Pocket Guides with new code examples and real projects to help tie everything you’ll learn together. Check it out.

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