Use Modernizr to test the new HTML5/CSS3 features, modernizrhtml5

Source: Internet
Author: User
Tags unsupported html5 boilerplate sessionstorage

Use Modernizr to test the new HTML5/CSS3 features, modernizrhtml5

HTML5, CSS3, and related technologies (such as canvas and web sockets) bring very useful features that can improve our web programs to a new level. These new technologies allow us to use only HTML, CSS, and JavaScript to build diverse forms pages that can run on tablets and mobile devices. Although HTML5 provides many new features, it is unrealistic to use these new technologies without considering the old version of browsers. The old version of browsers have been used for many years, we still need to consider the compatibility of these versions. The problem to be solved in this article is: when we use HTML5/CSS3 technology, how can we better deal with the problem of old browsers that do not support HTML5/CSS3 features.


Although we can write code to determine whether the browser supports some HTML5/CSS3 features, the Code is not very simple. For example, if you write code to determine that the 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 following, but it is easy to generate a bug in 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>

In the previous two examples, we checked one feature separately. If there are many HTML5/CSS3 features, we had to write multiple pieces of code for judgment. Fortunately, these codes do not depend on the sequence. Modernizr allows you to use a small amount of code to implement the above complex functions. Let's take a look at some important features of Modernizr:

Start using Modernizr

When I heard about Modernizr for the first time, I thought it meant modernized. I could add some new HTML5/CSS3 features on the old browser. In fact, Modernizr does not do this. It helps us improve our development practices. It uses a very fashionable method to help detect whether the browser supports some new features, you can even load additional scripts. If you are a web developer, it is a powerful weapon for you.

Modernizr official site: http://modernizr.com, 2 types of scripts you can use (Development and Custom production version ). The website provides a customized tool to generate only the detection functions you need, rather than a large and complete version that can be detected by everything. That is to say, you can minimize your scripts. Is an official website generation tool interface, you can see a lot of HTML5/CSS3 and related technology test functions can be selected.

After downloading your custom script, you can reference it like referencing a common js file, and then use it.

<script src="Scripts/Modernizr.js" type="text/javascript"></script>

 

Modernizr and HTML elements

After the Modernizr reference is added, it takes effect immediately. When running, it will add a batch of CSS class names on the html element. These class names mark the features supported by the current browser and the features not supported, the supported features directly display the name of the daily feature as a class (for example, canvas or websockets). The class displayed for unsupported features is "no-feature name" (for example: no-flexbox ). The following code shows the effect of running in Chrome:

The following code shows the effect of running IE9:

When Modernizr is used, the following code may occur (add no-js name to class ):

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, indicates whether the browser supports JavaScript. If not, no-js is displayed. If yes, no-js is deleted. Very nice, right?

Combined with HTML5/CSS3 features

You can directly use the class name generated by Modernizr in the

.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;}

If the browser supports box-shadows, Modernizr adds the boxshadow class to the
In addition to adding the corresponding class to the

$(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');    }});

Other CSS3 features can detect the results, such as opacity, rgba, text-shadow, CSS animations, CSS transitions, and multiple backgrounds, the complete HTML5/CSS3 probe list supported by Modernizr can be found at http://www.modernizr.com/docs.

Use Modernizr to load Script

In some browsers that do not support new features, Modernizr not only provides the above method to tell you, the load function is also provided to allow you to load some shim/polyfill scripts to achieve the supported purpose (For information about shim/polyfill, visit: https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills ). Modernizr provides a script loader to determine a function. If not, load the corresponding script. A separate script can also be found in the http://yepnopejs.com.

You can use the load () function of Modernizr to dynamically load scripts. The test attribute of this function indicates whether to test the new features supported. If the test is successful, load the yep Property setting script. If not, load the nope Property setting script. No matter whether it is supported or not, the script set in the both property will be loaded. The sample code is as follows:

Modernizr.load({    test: Modernizr.canvas,    yep:  'html5CanvasAvailable.js’,    nope: 'excanvas.js’,     both: 'myCustomScript.js' });

In this example, Modernizr checks whether the current browser supports the canvas feature. If so, it loads html5CanvasAvailable. js and myCustomScript. js, if not supported, will load excanvas. js (for versions earlier than IE9) script file to allow the browser to support the canvas function, and then load myCustomScript. js script.

Because Modernizr can load scripts, you can also use them for other purposes. For example, if you reference a third-party script (for example, Google and Microsoft provide jquery hosting for CDN Services) when loading fails, you can load the backup file. 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 local js file, if the file in the complete is not loaded successfully, it will load the needs-jQuery.js file.

Summary:


If you are using the latest HTML5/CSS3 to build your program, Modernizr is definitely a required tool. Using it can save a lot of code and test workload, and even implement the corresponding new features in Some browsers that do not support new features by loading additional scripts.

Copyright statement: This article is the original author of the http://www.zuiniusn.com, not allowed by the blogger can not be reproduced.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.