HTML5, CSS3 and related technologies such as canvas and web sockets have brought very useful features that can help our web programs improve a new level. These new technologies allow us to build diverse form pages that can run on tablets and mobile devices using only HTML, CSS and JavaScript. Although HTML5 provides many new features, it is not realistic to use these new technologies if we do not consider the old version of the browser. The old version of the browser has been used for many years, and we still need to consider the compatibility issues of these versions. The problem to be solved in this article is: when we use HTML5/CSS3 technology, how to better deal with the problem of old browsers that do not support HTML5/CSS3 features.
Although we can write code ourselves to determine whether the browser supports certain HTML5/CSS3 features, the code is not very simple. For example: writing code to determine that browser payment supports canvans, our code may be similar to the following:
<script> window.onload = function () { if (canvasSupported()) { alert('canvas supported'); } }; function canvasSupported() { var canvas = document.createElement('canvas'); return (canvas.getContext && canvas.getContext('2d')); }</script>If you want to determine whether local storage is supported, the code may be similar to the one below, but it is easy to cause bugs under Firefox.
<script> window.onload = function () { if (localStorageSupported()) { alert('local storage supported'); } }; function localStorageSupported() { try { return ('localStorage' in window && window['localStorage'] != null); } catch(e) {} return false; }</script>The first two examples are all checking for a feature. If there are many HTML5/CSS3 features, we have to write multiple copies of code to judge, but luckily, these codes do not depend on order. Modernizr allows you to implement the above complex functions with very little code. Let's take a look at some important features of Modernizr:
Get started with ModernizrThe first time I heard Modernizr, I thought it meant modernized, and could add some new HTML5/CSS3 features to older browsers. In fact, Modernizr is not doing this, it helps us improve our development practices, using a very funky method to help detect if the browser supports some new feature, and can even load additional scripts. If you are a web developer, it is a very awesome weapon for you.
Modernizr official site: http://modernizr.com, you can use both 2 types of scripts (development version and custom production version). The website provides a custom-demand tool to generate only the detection features you need, rather than a large and complete version that can detect everything, which means you can minimize your scripts. The following figure is the interface of the official website generation tool. You can see that many HTML5/CSS3 and related technologies can be selected.
After downloading your custom script, you can reference it like a normal js file, and then you can use it.
<script src=Scripts/Modernizr.js type=text/javascript></script>Modernizr and HTML elements
After adding the Modernizr reference, it takes effect immediately. When running, it will add a batch of CSS class names to the html element. These class names mark which features support and which features do not support in the current browser. The supported features will directly display the name of the feature of the day as a class (for example: canvas, websockets). The class displayed by the unsupported features is no-property name (for example: no-flexbox). The following code is the effect of running in Chrome:
<html class= js flexbox canvas canvastext webgl no-touch geolocation postmessage websqldatabase indexeddb hashchange history draganddrop websockets rgba hsla multiplebgs backgroundsize borderimage borderradius boxshadow textshadow opacity cssanimations csscolumns cssgradients cssreflections csstransforms csstransforms3d csstransitions fontface generatedcontent video audio localstorage sessionstorage webworkers applicationcache svg inlinesvg smil svgclippaths>
The following code is the effect of running under IE9:
<html class= js no-flexbox canvas canvas canvas canvastext no-webgl no-touch geolocation postmessage no-websqldatabase no-indexeddb hashchange no-history draganddrop no-websockets rgba hsla multiplebgs backgroundsize no-borderimage borderradius boxshadow no-textshadow opacity no-csssanimations no-csscolumns no-cssgradients no-cssreflections csstransforms no-csstransforms3d no-csstransitions fontface generatedcontent video audio localstorage sessionstorage no-webworkers no-applicationcache svg inlinesvg smil svg clippaths>
Using Modernizr, the following code may occur (add the no-js name to class):
<html class=no-js>
You can visit the (http://html5boilerplate.com) site to view HTML5 Boilerplate related content, or (http://initializr.com) to view Initializr related content, add no-js class to the html element, which tells the browser whether JavaScript is supported. If it is not supported, no-js will be displayed. If it is supported, no-js will be deleted. Very cool, right?
Use with HTML5/CSS3 featuresYou can directly use the class name generated by Modernizr in the <html> element to define the corresponding attributes in your css file to support the current browser. For example, the following code can display shadow in a browser that supports shadow shadow, and display standard borders in browsers that do not support:
.boxshadow #MyContainer { border: none; -webkit-box-shadow: #666 1px 1px 1px; -moz-box-shadow: #666 1px 1px 1px;} .no-boxshadow #MyContainer { border: 2px solid black;}Because if the browser supports box-shadows, Modernizr will add boxshadow class to the <html> element, and you can manage it to the corresponding div id. If not supported, Modernizr will add the no-boxshadow class to the <html> element, which shows a standard border. In this way, we can easily use the new CSS3 features on browsers that support CSS3 features, and continue to use the previous method on browsers that do not support them.
In addition to adding the corresponding class to the <html> element, Modernizr also provides a global Modernizr JavaScript object, which provides different properties to indicate whether a new feature is supported in the current browser. For example, the following code can be used to determine whether the browser supports canvas and local storage. It is very beneficial for multiple developers to develop and test under multi-version browsers, and everyone can unify the code.
$(document).ready(function () { if (Modernizr.canvas) { //Add canvas code } if (Modernizr.localstorage) { //Add local storage code }});The global Modernizr object can also be used to detect whether the CSS3 feature is supported. The following code is used to test whether border-radius and CSS transforms are supported:
$(document).ready(function () { if (Modernizr.borderradius) { $('#MyDiv').addClass('borderRadiusStyle'); } if (Modernizr.csstransforms) { $('#MyDiv').addClass('transformsStyle'); }});Some other CSS3 features can detect results, such as opacity, rgba, text-shadow, CSS animations, CSS transitions, multiple backgrounds, etc. The complete HTML5/CSS3 detectable list supported by Modernizr can be found at http://www.modernizr.com/docs as follows.
Loading Script Scripts with ModernizrOn some browsers that do not support new features, Modernizr not only provides the above method to tell you, but also provides the load function to allow you to load some shim/polyfill scripts to achieve support (for information about shim/polyfill, please visit: https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills). Modernizr provides a script loader to determine a function, and if it is not supported, the corresponding script will be loaded. A separate script can also be found at http://yepnopejs.com.
You can use Modernizr's load() function to dynamically load the script. The test attribute of the function indicates whether it is supported. If the test is successfully supported, the script set by the yep attribute is loaded. If it is not supported, the script set by the nope attribute will be loaded. Regardless of whether it is supported or not, the script set by the both attribute will be loaded. The example code is as follows:
Modernizr.load({ test: Modernizr.canvas, yep: 'html5CanvasAvailable.js ', nope: 'excanvas.js ', both: 'myCustomScript.js' });In this example, Modernizr will determine whether the current browser supports the canvas feature. If it is supported, it will load the two scripts html5CanvasAvailable.js and myCustomScript.js. If it is not supported, it will load the excanvas.js (used for versions before IE9) script file to make the browser support the canvas function, and then load the myCustomScript.js script.
Because Modernizr can load scripts, you can also use other uses, for example, if the third-party script you reference (such as Google and Microsoft that provide CDN services provide jquery hosting) fails to load, you can load alternate files. The following code is an example of loading jquery provided by Modernizr:
Modernizr.load([ { load: '//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js', complete: function () { if (!window.jQuery) { Modernizr.load('js/libs/jquery-1.6.4.min.js'); } } } }, { // This will wait for the fallback to load and // execute if it needs to. load: 'needs-jQuery.js' }]);This code will first load the jQuery file from Google CDN. If the download or loading fails, the complete function will be executed. First, determine whether the jQeury object exists. If it does not exist, Modernizr will load the defined native js file. If even the files in complete are not loaded successfully, the needs-jQuery.js file will be loaded.
Summarize:Modernizr is definitely a necessary tool if you are using the latest HTML5/CSS3 to build your program. Using it, you can save a lot of code and test work, and you can even implement the corresponding new features in the form of additional loading scripts for some browsers that do not support new features.
Original address: http://weblogs.asp.net/dwahlin/archive/2011/11/16/detecting-html5-css3-features-using-modernizr.aspx