Introduction
Modernizr is a JavaScript library that runs feature detection tests in the browser and reports which HTML5 and CSS3 features are available. Instead of relying on unreliable user-agent sniffing, it lets developers write conditional code paths and CSS rules based on actual browser capabilities.
What Modernizr Does
- Runs over 270 feature detection tests for HTML5 and CSS3 APIs
- Adds CSS classes to the html element indicating supported features
- Provides a JavaScript API to check feature availability programmatically
- Supports conditional resource loading for polyfills via Modernizr.load
- Generates custom builds containing only the tests you need
Architecture Overview
Modernizr executes small self-contained test functions that probe for specific browser capabilities by creating DOM elements, checking CSS properties, or calling APIs. Results are stored as boolean properties on the global Modernizr object and reflected as CSS classes on the document root element, enabling both JavaScript and CSS-based feature gating.
Self-Hosting & Configuration
- Install via npm or download a custom build from the project website
- Use the CLI or config JSON to select only needed detects and reduce bundle size
- Include the generated script in the document head before other scripts
- No server-side component needed; runs entirely in the browser
- Integrate with build tools via the modernizr webpack plugin or Gulp tasks
Key Features
- Accurate detection without user-agent string parsing
- Custom build system to minimize payload size
- CSS class injection for declarative progressive enhancement
- Asynchronous test support for non-blocking detection
- Extensible architecture for adding custom feature tests
Comparison with Similar Tools
- @supports (CSS) — Native CSS feature queries; covers CSS properties but not JavaScript APIs or HTML features
- caniuse-lite — Build-time browser support data; provides statistical compatibility info rather than runtime detection
- core-js — Provides polyfills for missing features rather than detecting them; complementary to Modernizr
- Browserslist — Defines target browser versions for build tools; works at compile time, not runtime
FAQ
Q: Is Modernizr still relevant with modern browsers? A: For new projects targeting only evergreen browsers, native @supports queries often suffice. Modernizr remains useful for projects that must support older browsers or need JavaScript API detection.
Q: Does Modernizr polyfill missing features? A: No. Modernizr only detects feature support. It can conditionally load polyfills, but it does not ship them itself.
Q: How large is a custom Modernizr build? A: A typical build with 10-20 detects compresses to under 5 KB gzipped, significantly smaller than the full library.
Q: Can I add my own feature tests? A: Yes. Modernizr.addTest() lets you register custom tests that integrate with the same CSS class and API infrastructure.