Testing for Features with Modernizr load
Problem
You’re using newer technologies, and you want to make sure the client can support the
technologies before you load them.
Solution
You can use a library such as Modernizr to handle basic HTML5/CSS differences be‐
tween browsers. But you can also use a companion tool, Modernizr.load, to test to see
if an existing technology is supported
As an example, if you want to incorporate touch events in your application, you can use
Modernizr to test whether they’re supported in an environment and only load the ap‐
plication script if they are. In the following code, the application is testing to see if the
touch events, covered in Chapter 18, are supported. If they are, the application script is
loaded:
Modernizr.load({ test: Modernizr.touch, yep : 'touchtest.js' });
EXPLAIN
Modern browser makers are highly competitive, which means that most of the modern
technologies we want to use are already part of the browser your user is most likely
using. Unfortunately, we can’t take it as given that every user is using the most modern
browser, and that’s where a concept like feature detection enters.
Years ago, when testing for browser differences, we’d check browser versions because
browser companies didn’t release new versions all that often. The idea of doing this
nowadays, when some of the companies seemingly release a new version every week, is
ludicrous.
Feature detection is a way of guaranteeing that the environment will support
your application, regardless of browser version or client.
Feature detection can be tedious, though, and tricky. That’s where a feature detection
tool like Modernizr.load comes in. It comes with a set of feature detection tests already
built in, as demonstrated in the solution.
And you can use Modernizer.load plugins to
check for others, or even create your own.
To use Modernizr.load, go to the Modernizr site, check the features you want to test
and/or support, and the site builds a custom library. To use the library, include the script
in the page (in the head element, preferably after your style elements), and then include
the links to your test scripts.
You can also use the software to load a polyfill library to manage differences:
Modernizr.load({ test: Modernizr.websockets, nope : 'websockets.js' });
You can list multiple JavaScript files, separated by commas, for both the yep and nope properties.
No comments:
Post a Comment