Feature Detection - Amazon Silk

Feature Detection

When you build a website, you want to deliver the best possible experience to all of your customers, no matter what browser and platform they're using. You can do this with feature detection. Feature detection is a content-delivery strategy predicated on feature availability, not browser functionality. Instead of checking to see if a customer is using "browser X version 1.1" and then assuming that this version of browser X supports some feature, you test for the feature directly and serve content accordingly.

Note

You can also use user agent detection to target content, but this approach can be problematic. User agent detection requires you to keep track of the browsers your customers use and the features that those browsers support. Those variables will change over time, so user agent detection isn't future proof. User agent detection can be useful if feature detection is expensive or if a particular feature is only partially implemented by a browser. But in most cases, feature detection is the right choice. For more information about user agent detection, see User Agent Strings and Detection.

How To Detect a Feature

There are several ways to detect features. You can write your own feature detection scripts, or you can use a helper library. Both methods are demonstrated below.

Test for Feature Support

The following code detects support for the HTML5 canvas element by testing one of the element's attributes (getContext). The attribute test is important because browsers can create elements that they don't actually support. If we can interact with an attribute, that gives us more information.

<!DOCTYPE html> <html> <body> <div>Test support for the HTML5 canvas element.</div> <script> function supportsCanvas() { return !!document.createElement('canvas').getContext; } if (supportsCanvas()) { alert('Your browser supports the canvas element.'); } else { alert('Your browser does not support the canvas element.'); } </script> </body> </html>

If our test for the getContext method returns true, we assume that canvas is supported. The test uses double negation !! to force a boolean value (true or false). For more on this canvas test and on the Modernizr test below, see Canvas in Mark Pilgrim's Detecting HTML5 Features.

Test for a Feature with Modernizr

You can also detect features by using Modernizr, a JavaScript library that identifies support for HTML5 and CSS3 features. It minimizes the amount of code you have to write. You can build a custom Modernizr library to test for specific features.

In an application, we need to serve content for the supported feature. And if the feature isn't supported, we need to have a fallback. Polyfills can help with this. Polyfills are JavaScript shims that approximate native browser functionality. Modernizr maintains a listing of HTML5 Cross Browser Polyfills.

Additional Resources