Feature Detection with Modernizr for Cross Browser Compatibility
By The Nerdy Geek, Community Contributor - September 17, 2022
While working with CSS, one of the major concerns is the inconsistent feature support among browsers. Modernizr is one such library that helps in getting rid of those inconsistencies by using Feature Detection. Interestingly, Modernizr doesn’t transform your code. However, it just enhances the code by adding specific CSS classes to your HTML tags.
This article explores what Modernizr is, its Feature Detection, and how to use it and ensure Cross Browser Compatibility for the websites.
- What is Modernizr, and Why do you need it?
- What is Modernizr feature detection?
- CSS3 Feature Detection with Modernizr
- Modernizr’s classes
- Using Modernizr with JavaScript
- HTML5 Feature Detection with Modernizr
- How Modernizr’s Feature Detection can be used to ensure Cross Browser Compatibility?
- Browser Compatibility for HTML5 features
- Browser Compatibility for CSS3 features
What is Modernizr, and Why do you need it?
Modernizr is a JavaScript library that automatically detects which features or, rather, web technologies are available in users’ browsers. For example, Modernizr can easily detect which HTML5 and CSS3 features are being supported by the visitor’s browsers.
Modernizr has a feature detection mechanism, using which, it allows you to easily customize your users’ experience based on their browser capabilities. Using the feature detection support, developers can test some of the newer technologies and provide fallbacks for browsers that do not support those technologies.
Modernizr is important because it provides an easy way to detect any new feature, whether or not it is compatible with the browser. This enables devs to take any corresponding action for delivering a consistent user experience.
For example, if your browser does not support a particular video feature, then you might just want to display a simple page design in its place for a seamless user experience. This is possible with Modernizr, as it provides information about whether the said feature is compatible or not. Hence, with Modernizr, you offer a consistent user experience to different users.
What is Modernizr feature detection?
In web development, developers always have to figure out whether a particular new feature would be available in the different browsers accessed by users or not. Without Modernizr, the dev might just have to use hit and trial and then check if the new feature works well with the said browser version.
This approach might be really cumbersome, and revisiting the same area of code, again and again, can even be very risky.
This is where Feature Detection comes into the picture. Feature Detection feature programmatically checks if the new feature works in the browser version and returns the result in True or False. Based on the method’s outcome, the dev can easily design the code further, and there will be absolutely no need to revisit the code even with multiple browser version launches.
CSS3 Feature Detection with Modernizr
Before deep diving into Feature Detection with Modernizr, let’s understand the three basic functions which Modernizr performs for Feature Detection:
- It creates a JavaScript object to validate whether a particular HTML or CSS feature is supported in a browser or not.
- It adds classes to indicate feature support that can be used to conditionally apply CSS styling rules to different elements.
- It allows a conditionally supply of custom JS scripts or polyfills to imitate the features which are lacking.
Modernizr’s classes
Modernizr, by default, sets classes for all of your tests on the root element, i.e., <html> for websites. This means adding a class for each feature when it is supported and adding it with a no-prefix when it is not supported. For example, .feature or .no-feature. Modernizr’s classes just make it easier enough to add features.
Lets take an example, if you want Modernizr’s feature detection for CSS Gradients, in that case, depending on the browser, the result will be either <html class=”cssgradients”> or <html class=”no-cssgradients”>.
Now that you have both of these two states, you can write CSS to cover both scenarios, as seen below:
.no-cssgradients
.no-cssgradients .header { background: url("images/radiobutton.png"); }
.cssgradients
.cssgradients .header { background-image: linear-gradient(cornflowerblue, rebeccapurple); }
- classPrefix
In Modernizr, you have an option to add a classPrefix inside your config in case Modernizr’s class name clashes with one of your pre-existing classes.
For example, consider the hidden detect, which adds a .hidden class in order to hide things. In case you want to achieve something similar, you can use the below in your configuration.
{ "classPrefix": "foo-", "feature-detects": ["dom/hidden"] }
With this configuration, instead of <html class=”hidden”>, you would get <html class=”foo-hidden”>.
- no-js
Modernizr by default will rewrite <html class=”no-js”> to <html class=”js”>. This is done in order to hide certain elements, which should otherwise be exposed only in environments that execute JavaScript. In case this change needs to be disabled. You can set enableJSClass to false in your config.
- enableClasses
In case you do not want Modernizr to add any of its classes, you can set enableClasses to false in your config. However, bear in mind that this does not have any effect on the .no-js update. So, in case you do not want that, you can set enableJSClass to false.
Using Modernizr with JavaScript
Modernizr keeps track of the results of all of its feature detections using the Modernizr object. This means that for each test, Modernizr adds a corresponding property.
if (Modernizr.newFeature) { showOffNewFeature(); } else { getTheSameOldExperience(); }
Helper methods in Modernizr
Modernizr also offers a lot of additional functions. Some of them are mentioned below
- Modernizr.on
Syntax
Modernizr.on(feature,cb)
Implementation
Modernizr.on('flash', function( result ) { if (result) { // the browser has flash } else { // the browser does not have flash } });
- Modernizr.addTest
Syntax
Modernizr.addTest(feature,test)
The most widely used way of creating one’s own feature detects is by calling Modernizr.addTest with a string (preferably lowercase and without any punctuation) and a function to be executed which returns a boolean result.
Implementation
Modernizr.addTest('itsMonday', function() { var d = new Date(); return d.getDay() === 2; });
In the above case, Modernizr.itsMonday will return true whenever it is Monday and false on every other day of the week. Note that the Modernizr feature detects functions are always in lowercase when they are added to the Modernizr object.
- Modernizr.atRule
Syntax
Modernizr.atRule(prop)
Implementation
var keyframes = Modernizr.atRule('@keyframes'); if (keyframes) { // keyframes are supported // could be `@-webkit-keyframes` or `@keyframes` } else { // keyframes === `false` }
HTML5 Feature Detection with Modernizr
Modernizr creates a global Modernizr JavaScript object that further allows us to query properties of that object in order to perform Feature Detection by calling Modernizr.<featurename>.
In order to test for canvas support, you can write the following:
<script> if (Modernizr.canvas) { alert("This browser supports HTML5 canvas!"); } </script>
You can also make this a little interesting by using an else statement as well.
<script> if (Modernizr.canvas) { alert("This browser supports HTML5 canvas!"); } else { alert("no canvas :("); } </script>
Once you try this with different browsers, you will easily get to know which browser versions are supporting HTML5 canvas and which aren’t.
How Modernizr’s Feature Detection can be used to ensure Cross Browser Compatibility?
With more and more websites making use of the modern HTML5 and CSS3 features, Modernizr has become an indispensable asset. This is because Modernizr with Feature Detection not just identifies which browser version can support the latest features. It also helps to provide a fallback for all those unsupported functionalities and features. As a result, it ensures a smooth user experience regardless of their browser version.
Browser Compatibility for HTML5 features
Let us understand the browser compatibility of the various HTML5 features or elements by using caniuse.com, which lists the compatibility of different browser versions for HTML5 elements.
As seen below, almost all desktop browsers, including Microsoft Edge and IE11, provide browser support for HTML5 elements. Except for a few older versions of Firefox and IE, overall, it enjoys quite vast browser support from different browsers.
Source: caniuse.com
Browser Compatibility for CSS3 features
The browser compatibility results for CSS3 features can be checked out using caniuse.com.
Except for the CSS3 attr() function, almost all CSS3 features enjoy good browser support from almost all the latest browser versions.
Source: caniuse.com
With Modernizr Feature Detection, you can decipher which element is cross browser compatible. This will help in finding a workaround to make the UX consistent and seamless when using elements not completely supported by all browsers and their versions.
Testing Cross Browser Compatibility
While Modernizr Feature Detection helps in identifying areas where certain elements/features are not compatible with the various browser versions, it is still important to test the browser compatibility of the application before making it live.
With BrowserStack, you can access 3000+ browsers and real devices (mobile and desktop) and enjoy a wide coverage for Cross Browser & Platform Testing. Using BrowserStack’s enormous range of devices and browsers, you can easily test your websites across different browser versions and ensure similar and consistent UI/UX behavior across multiple devices.
You can also leverage the power of automation testing to check cross-browser compatibility with BrowserStack as it integrates with most of the test automation frameworks such as Selenium, Cypress, Playwright, Puppeteer, etc., saving both time and cost incurred.
You can also save time by using parallel testing to run tests on different browser-device combinations simultaneously with BrowserStack. This allows devs and testers to build applications to retain and delight users through its seamless user experience.