Modernizr allows developers to start using HTML5 today with a high degree of compatibility even on older browsers.
A couple of weeks ago, I wrote about how I used Modernizr to add support for HTML5 elements to older browsers. Today, I will go more in-depth about Modernizr, because it gives developers the ability to use HTML5 today while addressing concerns about older browsers.
The Modernizr download screen allows for customization. (Click the image to enlarge.)
Aside from the built-in polyfills, Modernizr is used to detect features and make decisions based on what is detected (including loading the appropriate polyfills). If you need more polyfills, the Modernizr GitHub repository lists zillions of them. The nice thing about Modernizr is that it actually detects the availability of functionality, instead of simply checking out what user agent is being used and comparing it to a functionality chart. This ensures Modernizr's feature detection is always accurate.
It's really easy to use the feature detection to load polyfills. Once you have added Modernizr to your page, you can use the Modernizr.load() method to detect a feature and load the right files based on it. The basic syntax is:
yep: 'file to load if feature supported',
nope: 'file to load if feature not supported'});
The syntax can get more complicated as your needs become more sophisticated. You can use the && operator in your tests to make sure that multiple tests are passed before you load a script. This lets you bring in a pile of polyfills to compensate for a very out-of-date browser. Multiple resources can be loaded by specifying their names in array syntax (such as ['file 1', 'file 2']). When loading multiple resources, they will download in parallel. You can also use a "both" clause (or the "load" clause) to load resources regardless of whether the conditions are met, and a "complete" or "callback" clause to pass in code to be run when it is finished. The full documentation for the loading functionality is on the yesnopejs page.
It seems like every time I write about HTML5, a common question from developers is, "but when can I start using it?" The good news is, with careful use of Modernizr, you can start using HTML5 today with a high degree of compatibility even on older browsers.
Keep your engineering skills up to date by signing up for TechRepublic's free Software Engineer newsletter, delivered each Tuesday.