HTML and CSS Reference
In-Depth Information
proaches for detecting feature support vary widely, making it difficult to remember how to
test for each individual feature. Another issue with feature detection is that you may wish
to load certain external resources only if the user's browser supports (or doesn't support) a
given feature. We don't see a point, for example, to loading a large WebGL support frame-
work if the user's browser doesn't support WebGL. In a similar way, why should we load a
color-picker widget library if the user's browser includes a native widget that will be used
instead? Dynamic loading of external resources is possible, but the JavaScript for doing so
is hardly straightforward.
Enter Modernizr, a purpose-built JavaScript library for performing bulletproof feature de-
tection and dynamic loading. When you include Modernizr in a web page, you can detect
support for a feature using a much easier syntax. For example, to check to see if the user's
browser supports the Canvas element, you'd use the following:
if ( Modernizr . canvas ) {
//Canvas is supported, fire one up!
} else {
//Canvas is not supported, use a fallback
To detect Canvas support without Modernizr, you'd need to use the following:
if (!! document . createElement ( 'canvas' ). getContext ) {
//Canvas is supported, fire one up!
} else {
//Canvas is not supported, use a fallback
It's also simple to use Modernizr to dynamically load resources (either .js or .css files)
based on a feature test. Consider this example, in which Modernizr will determine if the
browser supports the localStorage API. If supported, it will load the localstorage.js file,
which would likely contain code that interacts with this API. Otherwise, it will load the
localstorage-polyfill.js file, which contains a fallback.
Modernizr . load ({
test : Modernizr . localstorage ,
Search WWH ::

Custom Search