Swiss Army Knife at the front: modernizr.js

Source: Internet
Author: User
Tags unsupported html5 boilerplate sessionstorage

Objective

The modernizr.js can both patch the old browser and ensure a progressively enhanced user experience for the new browser.

Role:

From a practical point of view, Modernizr does very little by default, except (in the case of your choice) for browsers that do not support HTML5 tags, such as ie6,7,8 append a HTML5 shim script developed by Remy Sharp to identify <aside>, In addition to the HTML5 elements such as <section>, the main thing it does is the browser ' function detection '. Therefore, it knows whether the browser supports various HTML5 and CSS3 features. : www.modernizr.com, Effect address: http://www.andthewinnerisnt.com/

HTML5, CSS3, and related technologies, such as canvas and web sockets, bring a very useful feature that allows our web programs to raise a new level. These new technologies allow us to build diverse forms pages that can run on tablets and mobile devices, using only html,css and JavaScript. HTML5 offers a lot of new features, but if we do not consider the old version of the browser is not very realistic with these new technologies, the old version of the browser has been used for many years, we still need to consider the compatibility of these versions. The problem with this article is how to better handle older browser issues that do not support the HTML5/CSS3 feature when we use HTML5/CSS3 technology.

Although we can write our own code to determine whether the browser supports certain HTML5/CSS3 features, the code is not very simple. For example: Write code to determine the browser payment support Canvans, our code may be similar to the following:

<Script>window.onload= function () {        if(canvassupported ()) {alert ('Canvas Supported');            }    }; functioncanvassupported () {varCanvas=Document.createelement ('Canvas'); return(Canvas.getcontext&&Canvas.getcontext ('2d')); }</Script>

If you want to determine whether local storage is supported (locally storage), the code may be similar to the following, but it is easy to generate bugs in Firefox.

<Script>window.onload= function () {        if(localstoragesupported ()) {alert ('Local Storage supported');    }    }; functionlocalstoragesupported () {Try {            return ('Localstorage' inchwindow&&window['Localstorage'] != NULL); }        Catch(e) {}return false; }</Script>

The first 2 examples are to check a feature separately, if there are many HTML5/CSS3 features, we have to write multiple code to judge, but fortunately, the code does not depend on the order. Modernizr allows you to implement these complex functions with very little code, so let's take a look at some of the important features of Modernizr.

Getting started with Modernizr

The first time I heard Modernizr, I thought it meant modernized, you can add some HTML5/CSS3 new features to the old version of the browser. In fact, Modernizr is not doing this, it's helping us improve our development practices, using a very fashionable approach to help detect whether a browser supports a new feature or even load additional script scripts. If you're a web developer, it's a great weapon for you.

MODERNIZR Official site: http://modernizr.com,2 Types of scripts you can use (both development and custom production versions). The Web site provides a custom requirement tool to generate only the probing functionality you need, rather than a chatty version of what can be probed, which means that you can minimize your script. is the official website Generation tool interface, you can see a lot of HTML5/CSS3 and related technology detection function can be selected.

Once you've downloaded your custom script, you can reference it just like a normal JS file, and then you can use it.

<src= "scripts/modernizr.js"  type= "Text/javascript"> </script>
Modernizr and HTML elements

Once the Modernizr reference is added, it takes effect immediately. When it runs, it adds a batch of CSS class names to the HTML elements that mark which features are supported by the current browser and which features are not supported, and the supported attributes directly display the name of the day attribute as a class (for example: canvas,websockets) , the unsupported attribute is displayed with the class "no-attribute name" (for example: No-flexbox). The following code is the effect of running under Chrome:

<class= "js flexbox canvas canvastext webgl no-touch geolocation postmessage               Websqldatabase indexeddb hashchange History draganddrop websockets rgba Hsla multiplebgs backgroundsize borderimag E Borderradius boxshadow Textshadow opacity cssanimations csscolumns cssgradients cssreflections CSSTRANSFO RMS Csstransforms3d csstransitions fontface  generatedcontent video audio localstorage sessionstorage Webworker S               applicationcache svg inlinesvg smil svgclippaths ">

The following code is the effect of running under IE9:

<class= "js no-flexbox canvas canvastext no-webgl no-touch geolocation               postmessage No-websqldatabase no-indexeddb hashchange no-history draganddrop no-websockets rgba hsla multiplebgs backgroundsiz E no-borderimage Borderradius boxshadow no-textshadow opacity no-cssanimations no-csscolumns No-cssgradien TS no-cssreflections csstransforms no-csstransforms3d no-csstransitions fontface generatedcontent Video AUD Io localstorage sessionstorage no-webworkers no-applicationcache svg inlinesvg smil svgclippaths ">

With Modernizr, the following code may appear (add No-js name to Class):

<class= "No-js">

You can visit the (http://html5boilerplate.com) site to view HTML5 boilerplate related content, or (http://initializr.com) view INITIALIZR related content, add No-js class to HTML element, is to tell the browser whether to support JavaScript, if not support the display of NO-JS, if supported to delete No-js. Pretty cool, huh?

used in conjunction with the HTML5/CSS3 feature

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

{    border: none;     -webkit-box-shadow: #666 1px 1px 1px;     -moz-box-shadow: #666 1px 1px 1px;} {border: 2px solid black;}         

Because if the browser supports Box-shadows, Modernizr will add the Boxshadow class to the

MODERNIZR provides a global Modernizr JavaScript object in addition to the corresponding class-to-

$ (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, and 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 results such as: opacity, Rgba, Text-shadow, CSS animations, css transitions, multiple backgrounds, etc. The complete list of HTML5/CSS3 Modernizr support can be found in the following http://www.modernizr.com/docs.

loading script scripts with Modernizr

In some browsers that do not support the new features, Modernizr not only provides you with the above-mentioned method, but also provides the load function that allows you to load some Shim/polyfill scripts to support the purpose (for information about Shim/polyfill, visit: https:// Github.com/modernizr/modernizr/wiki/html5-cross-browser-polyfills). MODERNIZR provides a script loader to judge a feature and load the appropriate script if it is not supported. Separate scripts can also be found in http://yepnopejs.com.

You can use the Modernizr load () function to load the script dynamically, the test property of the function is a new feature that indicates whether the test is supported, and if the test is successful, the script that loads the Yep property setting is loaded, and if the script that loads the Nope property setting is not supported, whether it is supported or not, The script that is set in the both property is loaded. The example code is as follows:

modernizr.load ({    Test:Modernizr.canvas,    yep:  'html5canvasavailable.js ',    ' excanvas.js ',     ' Mycustomscript.js ' });

In this example, MODERNIZR will determine whether the current browser supports the canvas feature, and if so, That will load both the html5canvasavailable.js and Mycustomscript.js scripts, which, if not supported, will load the script file Excanvas.js (for the previous version of IE9) to allow the browser to support the canvas feature before loading mycustomsc Ript.js script.

Because Modernizr can load scripts, you can also use them for other purposes, for example, if you reference third-party scripts (such as Google that provides CDN services and hosted by Microsoft jquery), you can load an alternate file if the load fails. The following code is an example of a load of jquery provided by Modernizr:

Modernizr.load ([    {        '//ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.js ',         function () {            if (!  Window.jquery) {                modernizr.load (' js/libs/jquery-1.6.4.min.js ');}}}    ,    {         // This would wait for the fallback to load        and // execute if it needs to.        Load: ' Needs-jquery.js '    }]);

The code will first load the jquery file from Google Cdn, if the download or load fails, the complete function will be executed, first of all to determine whether the Jqeury object exists, if not, MODERNIZR will load the defined native JS file, if the connection If the files in complete are not loaded successfully, the Needs-jquery.js file is loaded.

Use of Respond.js

Https://github.com/scottjehl/Respond the shim script so that it can support min-width and max-width, but there is a problem: The shim script will be loaded in every browser-whether they need it or not.

One workaround is to place the script file link in the IE conditional comment, as follows:

<!-- [If LTE IE 8]> <script src= "js/respond.min.js" type= "Text/javascript" ></script><! [EndIf]  -
Summary:

If you are using the latest HTML5/CSS3 to build your program, Modernizr is definitely a necessary tool. With it you can save a lot of code and test your workload, and you can even implement new features with additional load scripts for browsers that don't support new features.

Original address: Http://weblogs.asp.net/dwahlin/archive/2011/11/16/detecting-html5-css3-features-using-modernizr.aspx

Swiss Army Knife at the front: modernizr.js

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.