Modernizr
JavaScript library
Modernizr is a JavaScript library that detects the features available in a user's browser. This lets web pages avoid unsupported features by informing the user their browser is not supported or loading a polyfill. Modernizr aims to provide feature detection in a consistent and easy to use manner that discourages the use of failure-prone browser sniffing.
Overview
Many HTML5 and CSS 3 features are already implemented in at least one major browser. Modernizr determines whether the user's browser has implemented a given feature. This lets developers take advantage of new features that browsers support, yet create fallbacks for browsers that lack support. In both 2010 and 2011, Modernizr won the .net Award for Open Source App of the Year, and in 2011 one of its lead developers, Paul Irish, won the Developer of the Year award.
Function
Modernizr uses feature detection, rather than checking the browser's property, to discern what a browser can and cannot do. It considers feature detection more reliable since the same rendering engine may not necessarily support the same things in two different browsers using that engine. In addition, some users change their user agent string to get around websites that block features for browsers with specific user agent settings, despite their browsers having the necessary capabilities.
Modernizr runs feature tests in the browser and stores the results on a global JavaScript object named Modernizr. It also adds matching classes to the root <html> element, so JavaScript and CSS can use different code paths depending on what the browser supports.
Some Modernizr tests need more than a simple property check. For those cases, Modernizr can create temporary elements or inject test styles, then check how the browser handles them. This lets it detect support for features that are only visible through actual DOM or CSS behavior.
Many tests in the documentation come with a small code sample to illustrate how a specific test can be used in web development workflow.
Running
When it runs, it creates a global object called Modernizr that contains a set of Boolean properties for each feature it can detect. For example, if a browser supports the canvas API, the Modernizr.canvas property will be true. If the browser does not support the canvas API, the Modernizr.canvas property will be false:
Limitations
The library is simply a feature-detection method and as such, does not add missing functionality to older browsers.
Examples
Modernizr JavaScript example
CSS example
Adapted from the Wikipedia article, CC BY-SA 4.0. Continue on Wikipedia
Go deeper
Ideas this article links to.
- JavaScriptHigh-level programming language
- Web browserSoftware used to access websites
- JavaScript libraryPackage of JavaScript code
- Polyfill (programming)Code to implement features in web browsers that do not support them
- Feature detection (web development)Web development technique for determining environment functionalities