February 22, 2012 1

A simple design pattern for feature detection with non-dependant Modernizr support

By

Modernizr is the gold standard for client side feature detection and is widely used but what if you’re writing a JavaScript library and want to minimise the dependencies? Here’s a simple design pattern for feature detection with non-dependant Modernizr support.

In v1.3 of Flux Slider I added support for Modernizr, prior to this Flux just used some simple test I’d written to detect features. I wanted to make use of the advanced feature detection when the library was available but to also not require others to use Modernizr in order to use Flux.

To implement non-dependant support I modified my feature test code to first check for Modernizr, use it where possible but fallback to my own tests where not.

The coding required is pretty trivial but I think its a useful design pattern to adopt.

Example

myApp.browser = {
    supportsTransitions: false,
    supports3d: false
};

// Detect required browser features
(function() {
    // Check for CSS Transition support
    if(window.Modernizr && Modernizr.csstransitions !== undefined) {
        myApp.browser.supportsTransitions = Modernizr.csstransitions;
    }
    else {
        // Custom detect code
    }

    // Check for 3D CSS support
    if(window.Modernizr && Modernizr.csstransforms3d !== undefined) {
        myApp.browser.supports3d = Modernizr.csstransforms3d;
    }
    else {
        // Custom detect code
    }
});

If you want to see how Flux implements this take a look at flux.browser.js on GitHub.

Whats the benefit?

Modernizr is an established open source library, trusted by some of the nets largest sites. Its sole purpose is to accurately detect features across a range of browsers and to keep up with new versions (and possible new quirks!) as they are released.

Whilst I’m happy to write some simple tests to check for the features that Flux requires, I’m never going to be able to replicate the time and research that has gone into Modernizr.

Essentially, feature detection for Flux will be adequate without Modernizr but will be even more accurate and cover more edge cases with it! A case in point is the recent release of Firefox10 which added support for 3D transforms. My detection code failed to recognise this but anyone using Flux with Modernizr would have had access to its 3D effects on release day without having to wait for me to update my code.