HTML and CSS Reference
In-Depth Information
Client-Side Feature Detection
JavaScript-based feature detection is often implemented by creating a DOM element to
see if it exists or behaves as expected, for example:
detectCanvas () ? showGraph () :
showTable ();
function detectCanvas () {
var canvas = document . createElement ( "canvas" );
return canvas . getContext ? true : false ;
}
This snippet creates a canvas element and checks to see if it supports the getContext
property. Checking a property of the created element is a must, because browsers will
allow you to create any element in the DOM, whether it's supported or not.
This approach is one of many, and today we have open source, community-backed
frameworks that do the heavy lifting for us. Here's the same code as above, implemented
with the Modernizr framework:
Modernizr . canvas ? showGraph ()
: showTable ();
Feature-detection frameworks may come at a cost, however. Suppose you are running
a series of tests on the browser window before the page is rendered. This can get ex‐
pensive: running the full suite of Modernizr detections, for example, can take more than
30 milliseconds to run per page load. You must consider the costs of computing values
before DOM render and then modifying the DOM based on the framework's findings.
When you're ready to take your app to production, make sure you're not using the
development version of your chosen feature detection library.
On the plus side, frameworks like Modernizr provide a build tool that enables you to
pick and choose the features your app must have ( Figure 4-2 ). You can select exactly
which features you want to detect, and thereby reduce the overall detection footprint in
a production environment.
Feature-detection performance also depends on the devices and browsers you are tar‐
geting. For example, running a feature-detection framework on a first-generation
smartphone or old BlackBerry could crash the browser and cause your app to fail com‐
pletely. Take the time to tweak feature detection to gain top performance on your target
browsers.
Search WWH ::




Custom Search