Convert Figma logo to code with AI

Modernizr logoModernizr

Modernizr is a JavaScript library that detects HTML5 and CSS3 features in the user’s browser.

25,724
2,976
25,724
192

Top Related Projects

A working implementation of css grids for current browsers.

This script is the defacto way to enable use of HTML5 sectioning elements in legacy Internet Explorer.

11,311

A fast & lightweight polyfill for min/max-width CSS3 Media Queries (for IE 6-8, and more)

A JavaScript polyfill for Flexbox

Parse CSS and add vendor prefixes to rules by Can I Use

A suite of polyfills supporting the HTML Web Components specs

Quick Overview

Modernizr is a JavaScript library that detects HTML5 and CSS3 features in the user's browser. It allows developers to build websites with progressive enhancement, providing a better experience for users with modern browsers while ensuring basic functionality for those with older ones.

Pros

  • Easy to use and implement in web projects
  • Customizable build process to include only needed feature detections
  • Widely adopted and well-maintained
  • Helps create more accessible and backwards-compatible websites

Cons

  • Can slightly increase initial page load time
  • Some detections may become outdated as browser technologies evolve
  • Overreliance on feature detection can lead to complex conditional code

Code Examples

  1. Detecting CSS flexbox support:
if (Modernizr.flexbox) {
  // Use flexbox layout
} else {
  // Use fallback layout
}
  1. Checking for WebGL support:
if (Modernizr.webgl) {
  // Initialize WebGL content
} else {
  // Show alternative content or message
}
  1. Loading polyfills based on feature detection:
Modernizr.on('indexeddb', function(result) {
  if (!result) {
    // Load IndexedDB polyfill
    loadScript('path/to/indexeddb-polyfill.js');
  }
});

Getting Started

  1. Install Modernizr using npm:
npm install modernizr
  1. Create a custom build configuration file (e.g., modernizr-config.json):
{
  "feature-detects": [
    "css/flexbox",
    "canvas",
    "geolocation"
  ]
}
  1. Generate a custom Modernizr build:
npx modernizr -c modernizr-config.json -d ./js/modernizr-custom.js
  1. Include the generated file in your HTML:
<script src="js/modernizr-custom.js"></script>
  1. Use Modernizr in your JavaScript:
if (Modernizr.flexbox) {
  // Flexbox is supported
} else {
  // Flexbox is not supported
}

Competitor Comparisons

A working implementation of css grids for current browsers.

Pros of css-grid-polyfill

  • Specifically focused on CSS Grid layout, providing comprehensive support for this modern feature
  • Allows developers to use CSS Grid in older browsers without changing their code
  • Lightweight and easy to integrate into existing projects

Cons of css-grid-polyfill

  • Limited in scope compared to Modernizr's broader feature detection capabilities
  • May require more frequent updates to keep up with evolving CSS Grid specifications
  • Potentially higher performance overhead when used extensively in complex layouts

Code Comparison

css-grid-polyfill:

cssGridPolyfill.init({
  forceGridMode: 'auto',
  onlyLegacy: true,
  verbose: false
});

Modernizr:

Modernizr.addTest('cssgrid', function() {
  return Modernizr.testAllProps('grid-template-rows');
});

Summary

css-grid-polyfill is a specialized tool for enabling CSS Grid support in older browsers, offering a focused solution for developers working with modern layout techniques. It's lightweight and easy to implement but has a narrower scope compared to Modernizr.

Modernizr, on the other hand, provides a comprehensive feature detection library for various HTML5 and CSS3 features, including CSS Grid. It offers broader compatibility testing but may require additional polyfills for full feature support.

Choose css-grid-polyfill for projects specifically focused on CSS Grid layouts, while Modernizr is better suited for projects requiring detection and support for a wide range of modern web features.

This script is the defacto way to enable use of HTML5 sectioning elements in legacy Internet Explorer.

Pros of html5shiv

  • Lightweight and focused specifically on enabling HTML5 elements in older browsers
  • Simple implementation with a single script include
  • Minimal impact on page load times due to its small size

Cons of html5shiv

  • Limited functionality compared to Modernizr's broader feature detection capabilities
  • Requires additional polyfills for full HTML5 support in older browsers
  • Less actively maintained and updated compared to Modernizr

Code Comparison

html5shiv:

<!--[if lt IE 9]>
  <script src="html5shiv.js"></script>
<![endif]-->

Modernizr:

Modernizr.on('webp', function (result) {
  if (result) {
    // WebP is supported
  } else {
    // WebP is not supported
  }
});

html5shiv focuses solely on enabling HTML5 elements in older browsers, while Modernizr provides a more comprehensive feature detection system. html5shiv is simpler to implement but offers less functionality. Modernizr allows for more granular feature detection and provides a wider range of polyfills, making it more suitable for complex projects requiring extensive browser compatibility. However, this comes at the cost of a larger file size and potentially more complex implementation.

11,311

A fast & lightweight polyfill for min/max-width CSS3 Media Queries (for IE 6-8, and more)

Pros of Respond

  • Lightweight and focused solely on min/max-width media query polyfill
  • Simple implementation for basic responsive design support in older browsers
  • Faster loading and execution due to its smaller size and specific purpose

Cons of Respond

  • Limited functionality compared to Modernizr's comprehensive feature detection
  • Only supports min-width and max-width media queries
  • No longer actively maintained (last commit in 2016)

Code Comparison

Respond:

respond.mediaQueriesSupported = function(){
    return !!(w.matchMedia && w.matchMedia("only all").matches);
};

Modernizr:

Modernizr.addTest('mediaqueries', function() {
    return !!window.matchMedia || !!window.msMatchMedia;
});

Summary

Respond is a lightweight polyfill specifically for min/max-width media queries in older browsers, while Modernizr is a comprehensive feature detection library. Respond is simpler and faster for basic responsive design support, but Modernizr offers a wider range of feature detection capabilities. Modernizr is actively maintained, whereas Respond's development has ceased. Choose based on your project's specific needs and browser support requirements.

A JavaScript polyfill for Flexbox

Pros of Flexibility

  • Focused specifically on flexbox support, providing a lightweight solution
  • Simpler implementation for projects that only need flexbox polyfills
  • Actively maintained with recent updates

Cons of Flexibility

  • Limited scope compared to Modernizr's broader feature detection
  • Less community support and fewer contributors
  • May require additional polyfills for other modern CSS features

Code Comparison

Flexibility:

flexibility(document.documentElement);

Modernizr:

Modernizr.addTest('flexbox', function() {
  return Modernizr.testAllProps('flexBasis', '1px', true);
});

Key Differences

  • Modernizr offers comprehensive feature detection for various HTML5 and CSS3 features, while Flexibility focuses solely on flexbox support
  • Modernizr provides a customizable build process, allowing developers to include only needed tests, whereas Flexibility is a single-purpose library
  • Modernizr has a larger community and more extensive documentation, making it easier to find support and resources

Use Cases

  • Choose Flexibility for projects that specifically need flexbox polyfills and want a lightweight solution
  • Opt for Modernizr when broader feature detection is required or when working on larger projects that may benefit from its extensive capabilities and community support

Parse CSS and add vendor prefixes to rules by Can I Use

Pros of Autoprefixer

  • Automatically adds vendor prefixes to CSS properties, saving time and reducing manual work
  • Integrates seamlessly with build tools and CSS preprocessors
  • Regularly updated to support the latest browser versions and CSS features

Cons of Autoprefixer

  • Focuses solely on CSS prefixing, lacking feature detection capabilities
  • May add unnecessary prefixes for modern browsers, potentially increasing CSS file size
  • Requires additional setup and configuration in the build process

Code Comparison

Modernizr:

Modernizr.on('webp', function(result) {
  if (result) {
    // WebP is supported
  } else {
    // WebP is not supported
  }
});

Autoprefixer:

/* Input CSS */
.example {
  display: flex;
}

/* Output CSS */
.example {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
}

Summary

Modernizr is a feature detection library for HTML5 and CSS3, while Autoprefixer is a PostCSS plugin that adds vendor prefixes to CSS rules. Modernizr helps developers detect browser support for various features, enabling fallback strategies. Autoprefixer, on the other hand, simplifies cross-browser compatibility by automatically adding necessary prefixes to CSS properties. While Modernizr offers broader feature detection capabilities, Autoprefixer excels in streamlining CSS prefix management, making it an essential tool for many frontend developers.

A suite of polyfills supporting the HTML Web Components specs

Pros of webcomponentsjs

  • Focuses specifically on Web Components, providing a more specialized solution
  • Offers polyfills for broader browser support of Web Components
  • Actively maintained with regular updates and improvements

Cons of webcomponentsjs

  • Limited to Web Components functionality, less versatile than Modernizr
  • May require additional libraries for feature detection beyond Web Components
  • Potentially larger file size when including all polyfills

Code Comparison

Modernizr:

if (Modernizr.webgl) {
  // WebGL is supported
} else {
  // WebGL is not supported
}

webcomponentsjs:

if ('customElements' in window) {
  // Custom Elements are supported
} else {
  // Load polyfill
  import('@webcomponents/custom-elements');
}

Summary

Modernizr is a broader feature detection library, while webcomponentsjs focuses specifically on Web Components support. Modernizr offers a wide range of feature checks across various web technologies, making it more versatile for general use. On the other hand, webcomponentsjs provides specialized polyfills and support for Web Components, making it a better choice for projects heavily relying on this technology. The choice between the two depends on the specific needs of the project and the desired balance between versatility and specialization.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Modernizr

Modernizr is a JavaScript library that detects HTML5 and CSS3 features in the user’s browser.

npm version Build Status codecov Inline docs

Modernizr tests which native CSS3 and HTML5 features are available in the current UA and makes the results available to you in two ways: as properties on a global Modernizr object, and as classes on the <html> element. This information allows you to progressively enhance your pages with a granular level of control over the experience.

Breaking changes with v4

  • Dropped support for node versions <= 10, please upgrade to at least version 12

  • Following tests got renamed:

    • class to es6class to keep in line with the rest of the es-tests
  • Following tests got moved in subdirectories:

    • cookies, indexeddb, indexedblob, quota-management-api, userdata moved into the storage subdirectory
    • audio moved into the audio subdirectory
    • battery moved into the battery subdirectory
    • canvas, canvastext moved into the canvas subdirectory
    • customevent, eventlistener, forcetouch, hashchange, pointerevents, proximity moved into the event subdirectory
    • exiforientation moved into the image subdirectory
    • capture, fileinput, fileinputdirectory, formatattribute, input, inputnumber-l10n, inputsearchevent, inputtypes, placeholder, requestautocomplete, validation moved into the input subdirectory
    • svg moved into the svg subdirectory
    • webgl moved into the webgl subdirectory
  • Following tests got removed:

    • touchevents: discussion
    • unicode: discussion
    • templatestrings: duplicate of the es6 detect stringtemplate
    • contains: duplicate of the es6 detect es6string
    • datalistelem: A dupe of Modernizr.input.list

New Asynchronous Event Listeners

Often times people want to know when an asynchronous test is done so they can allow their application to react to it. In the past, you've had to rely on watching properties or <html> classes. Only events on asynchronous tests are supported. Synchronous tests should be handled synchronously to improve speed and to maintain consistency.

The new API looks like this:

// Listen to a test, give it a callback
Modernizr.on("testname", function (result) {
  if (result) {
    console.log("The test passed!");
  } else {
    console.log("The test failed!");
  }
});

We guarantee that we'll only invoke your function once (per time that you call on). We are currently not exposing a method for exposing the trigger functionality. Instead, if you'd like to have control over async tests, use the src/addTest feature, and any test that you set will automatically expose and trigger the on functionality.

Getting Started

  • Clone or download the repository
  • Install project dependencies with npm install

Building Modernizr

From javascript

Modernizr can be used programmatically via npm:

var modernizr = require("modernizr");

A build method is exposed for generating custom Modernizr builds. Example:

var modernizr = require("modernizr");

modernizr.build({}, function (result) {
  console.log(result); // the build
});

The first parameter takes a JSON object of options and feature-detects to include. See lib/config-all.json for all available options.

The second parameter is a function invoked on task completion.

From the command-line

We also provide a command line interface for building modernizr. To see all available options run:

./bin/modernizr

Or to generate everything in 'config-all.json' run this with npm:

npm start
//outputs to ./dist/modernizr-build.js

Testing Modernizr

To execute the tests using mocha-headless-chrome on the console run:

npm test

You can also run tests in your browser of choice with this command:

npm run serve-gh-pages

and navigate to these two URLs:

http://localhost:8080/test/unit.html
http://localhost:8080/test/integration.html

Integrating Modernizr with Build Tools

This section provides guidance on how to integrate Modernizr with various build tools and frameworks, making it easier to use in your projects.

1. Integrating with Webpack

To integrate Modernizr with Webpack, follow these steps:

  1. Install Modernizr:

    npm install modernizr --save
    
  2. Create a Modernizr Configuration File: Create a file named modernizr-config.js in your project root:

    module.exports = {
      "feature-detects": [
        "test/feature1",
        "test/feature2",
        // Add more feature detects as needed
      ]
    };
    
  3. Update Webpack Configuration: Modify your Webpack configuration file (e.g., webpack.config.js) to include the Modernizr plugin:

    const ModernizrWebpackPlugin = require('modernizr-webpack-plugin');
    
    module.exports = {
      // Other configurations...
      plugins: [
        new ModernizrWebpackPlugin({
          "feature-detects": [
            "test/feature1",
            "test/feature2"
          ]
        })
      ]
    };
    
  4. Build Your Project: Run your Webpack build process:

    npm run build
    

2. Integrating with Gulp

If you are using Gulp, you can integrate Modernizr as follows:

  1. Install Modernizr:

    npm install modernizr --save-dev
    
  2. Create a Gulp Task: In your gulpfile.js, add a task to build Modernizr:

    const gulp = require('gulp');
    const modernizr = require('modernizr');
    
    gulp.task('modernizr', function() {
      return modernizr.build({
        "feature-detects": [
          "test/feature1",
          "test/feature2"
        ]
      }).pipe(gulp.dest('dist/'));
    });
    
  3. Run the Gulp Task: Execute the task to generate the Modernizr build:

    gulp modernizr
    

3. Integrating with Parcel

For projects using Parcel, you can integrate Modernizr as follows:

  1. Install Modernizr:

    npm install modernizr --save
    
  2. Create a Modernizr Configuration File: Similar to the Webpack setup, create a modernizr-config.js file:

    module.exports = {
      "feature-detects": [
        "test/feature1",
        "test/feature2"
      ]
    };
    
  3. Update Parcel Configuration: You can use a plugin like parcel-plugin-modernizr to integrate Modernizr:

    npm install parcel-plugin-modernizr --save-dev
    
  4. Build Your Project: Run Parcel to build your project:

    parcel build index.html
    

Conclusion

Integrating Modernizr with your build tools can enhance your web applications by allowing you to detect and respond to the capabilities of the user's browser. Follow the steps above to set up Modernizr with your preferred build tool.

For more information, refer to the Modernizr documentation.

Code of Conduct

This project adheres to the Open Code of Conduct. By participating, you are expected to honor this code.

License

MIT License

NPM DownloadsLast 30 Days