JS Library Modernizr Introduction and use _ Other

Source: Internet
Author: User

Traditional browsers are not being completely replaced, making it difficult for you to embed the latest CSS3 or HTML5 functionality into your site. Modernizr is precisely to solve this problem came into being, as an open source JavaScript library, Modernizr detect browser to CSS3 or HTML5 function support. Instead of trying to add features that are not supported by older browsers, MODERNIZR allows you to modify the page design by creating an optional style configuration. It can also simulate features that are not supported by older browsers by loading custom scripts.

What is Modernizr?

Modernizr is an open source JS library that makes it easier for designers to develop different levels of experience based on different guest browsers (meaning differences in support for new standards). It enables designers to exploit HTML5 and CSS3 features in browsers that support HTML5 and CSS3 without sacrificing the control of browsers that do not support these new technologies.

When you embed a MODERNIZR script in a Web page, it detects whether the current browser supports CSS3 features, such as @font-face, Border-radius, Border-image, Box-shadow, Rgba (), and so on. It also detects whether HTML5 features are supported-such as audio, video, local storage, and new <input> tag types and attributes. On the basis of obtaining this information, you can use them on browsers that support these features to decide whether to create a fallback based on JS or to gracefully demote those browsers that are not supported. In addition, Modernizr can also enable IE to support CSS styles for HTML5 elements so that developers can immediately use these more semantically labeled tags.

Modernizr is simple and easy to use, but not omnipotent. Successful use of Modernizr depends largely on your CSS and JavaScript skills.

The main problem with HTML 5 and CSS 3 is not the degree of popularity and the differences between browsers, but rather the first understanding of what these differences are. Once clear, developers can address these limitations with graceful demotion (graceful degradation) technology. For this reason, many developers turn to open source project Modernizr.

Instead of detecting the user-agent string, Modernizr uses a series of tests to determine the browser's characteristics. Within a few milliseconds it can execute more than 40 tests and record the result as a property in an object named Modernizr. This information allows developers to detect whether a feature they are prepared to use is supported by browsers and processed accordingly.

In MODERNIZR version 2.0, it added a conditional resource loader (conditional resource loader) for JavaScript and CSS. The resource loader accepts three parameters, the first is an expression, and enumerates the required attributes. The second parameter is a list of JavaScript and CSS files that are loaded if the expression returns TRUE. The third parameter is a list of alternate files if the required attribute does not exist.

In addition to graceful demotion, the loader can also be used to introduce Polyfill. Allow me to explain to my friends who are not quite familiar with Pollyfill that Pollyfill is "a JavaScript gasket (SHIM) that simulates the standard API for older browsers." While this approach is not always recommended, Pollyfill can be used to add support for most HTML 5 features (Modernizr detected). Here, Polyfill is used to fill the vulnerabilities of browser functionality. Sometimes, Modernizr can perform this task seamlessly. But in essence, this is just a patch work, so you can't rely on it to produce exactly the same results that the browser does.

To improve performance, developers can customize Modernizr to perform the tests required by the site. This can be done through the Modernizr download page, which also displays a list of features that can be detected. The GitHub website also marked with an inability to detect features and possible solutions.

Modernizr is developed based on progressive enhancement theory, so it supports and encourages developers to create their sites on a level-by-layer basis. Everything starts with an idle foundation with JavaScript applied, adding an enhanced application layer one by one. Because of the use of Modernizr, you can easily know what the browser supports.

The principle of Modernizr

Modernizr uses JavaScript to detect features supported by browsers, but instead of dynamically loading different style sheets using JavaScript, it uses very simple techniques to add classes to the

For example, if the page supports the Box-shadow property, then Modernizr adds the Boxshadow class. If not, it is added using the No-boxshadow class as an alternative.

Because browsers ignore CSS properties that they cannot recognize, you can safely use the Box-shadow property according to your basic style rules, but you need to add a separate descendant selector to the older browser in the following format:

. no-boxshadow img {/* Styles for browsers that don ' t support Box-shadow */}

Only browsers that do not support Box-shadow will have No-boxshadow classes, so other browsers will not apply this style rule.

The following table lists the class names used by MODERNIZR to indicate support for CSS3. If a feature is not supported, the name of the corresponding class is prefixed with no-.

CSS Features

Modernizr Class (properties)

@font-face Fontface
: : beforE and :: after pseudo-elements Generatedcontent
Background-size Backgroundsize
Border-image Borderimage
Border-radius Borderradius
Box-shadow Boxshadow

CSS Animations

Cssanimations

CSS 2D Transformations

Csstransforms

CSS 3D Transformations

Csstransforms3d

CSS transitions

Csstransitions

Flexible box layout

Flexbox

Gradients

Cssgradients
Hsla () Hsla

multi-column layout

Csscolumns

Multiple backgrounds

Multiplebgs
Opacity Opacity

Reflection

Cssreflections
RGBA () Rgba
Text-shadow Textshadow

Regardless of where a particular CSS property is tested, the class name and property name are the same, but this requires that any hyphen or parenthesis be removed. Other classes are named after the CSS3 module they refer to.

The use of Modernizr

1. Download

First download the latest stable version of Modernizr from Www.modernizr.com. Add it to the

<script src= "Modernizr-1.5.min.js" ></script> 2. class to add "No-js" to the

<! DOCTYPE html>

When Modernizr runs, it turns this "No-js" class into "JS" to let you know it's already running. Modernizr does not just do this, it adds class classes for all the features it detects, and if the browser does not support an attribute, it will prefix the class name with "no-" for that attribute.
Add No-js class to HTML element, is to tell the browser whether to support JavaScript, if not supported on the display NO-JS, if the support to delete the No-js
If you use Dreamweaver's live Code at this point, you can see that Modernizr adds a lot of classes that indicate browser functionality, as shown in the following figure

As shown in the figure, the No-js class has been replaced by the JS class, which indicates that JavaScript is enabled.

If your Dreamweaver version does not have Live code (or you are using a different HTML editor), you can check the generated code using the development tools provided by most new browsers or the Firebug provided by the Firefox browser.

3. Use case 1--display shadow in browsers that support shadow shading, unsupported browsers display standard borders

Copy Code code as follows:

. 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

4. Use case 2--to test local storage

In addition to adding the corresponding class to

<script> window.onload = function () {if (localstoragesupported ()) {
   alert (' Local storage supported ');
 }  
};

function localstoragesupported () {
 try {return (' localstorage ' in Window && window[' localstorage ')!= nul  l);
 }catch (e) {} return
 false;

We can unify the code

 $ (document). Ready (function () { 
 if (modernizr.canvas) {//add Canvas code} 
 if (modernizr.localstorage) { 
 //script to run if local storage is 
 } else { 
 //script to run if local storage are not supported
  
 }
});

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 ');
 

Audio and video, the return value is a string that indicates that the browser can handle a particular type of confidence level. According to the HTML5 specification, an empty string indicates that the type is not supported. If the type is supported, the return value is "maybe" or "probably". For example:

if (Modernizr.video.h264 = = "") { 
//H264 is not supported
}

4. Use case 3--use Modernizr to verify HTML5 required form fields

HTML5 adds a number of new form properties, such as autofocus, which automatically places the cursor in a specified field when the page is first loaded. Another useful property is required, which prevents a HTML5-compliant browser from submitting a form if a required field is left blank.

Figure 1. The script detected a required field in a browser that does not support new properties

Figure 2. The script detected a required field in a browser that does not support new properties

Before submitting the form, the HTML5 compatible browser checks whether the required fields are filled in

Window.onload = function () {//Get the form and its input elements var form = document.forms[0], inputs = Form.element S If no, put the "autofocus" in the "the" "  Modernizr.input.autofocus) {//Because autofocus is not supported, the condition evaluates to True and Inputs[0].focus () places the cursor in the first input field inputs[0].focus (); }//If required not supported, emulate it if (!
        Modernizr.input.required) {form.onsubmit = function () {var required = [], Att, Val; Loop through input elements looking for required for (var i = 0; i < inputs.length; i++) {att =           Inputs[i].getattribute (' required '); If required, get the value and trim whitespace if (att!= null) {val = inputs[i].value;// 
                  If the value is empty, add to required array if (Val.replace (/^\s+|\s+$/g, ') = = ') {
                Required.push (Inputs[i].name); }}//Show alert if required array contaIns any elements if (Required.length > 0) {alert (' The following fields are required: ' + required.join (', ') 
      )); 
    Prevent the form from being submitted return false;
 }   }; } 
}

The code produces a function that, when the form is submitted, can traverse all the input elements in order to find fields with the required attribute. When it finds a field, it removes the opening and trailing whitespace from the value, and if the result is an empty string, it adds the result to the required array. After all the fields have been checked, if the array contains some elements, the browser displays a warning about the missing field names and blocks the submission of the form.

Create a custom version

When you are ready to deploy your site, it is recommended to create a MODERNIZR custom production version that contains only those elements that you actually need. This reduces the size of the Modernizr library from 44KB to 2KB according to the function you have chosen. The scope of the current option is shown in the figure.

Such as:

    1. Click http://www.modernizr.com/download/. This will open the interface as shown in the previous illustration.
    2. In the CSS3 category, select Box-shadow and CSS columns.
    3. In the HTML5 category, select the Input Attributes.
    4. In the Extra category, deselect HTML5 Shim/iepp.
    5. Make sure that the following options are selected in the Extra category (they should have been automatically selected).
      • Modernizr.load (Yepnope.js)
      • ADD CSS Classes
      • Modernizr.testprop ()
      • Modernizr.testallprops ()
      • Modernizr._domprefixes
    1. Click the Generate button.
    2. When the custom script is ready (typically within a or two seconds), a Download button appears next to the Generate button. Click the Download button and save the file in the JS folder of the sample Web site. The download page gives the production script a filename, such as modernizr.custom.79475.js, but you might want to give it a more meaningful name. In the sample file, the name I use is modernizr.adc.js.
    3. Replace the link modernizr.js in css_support.html and required.html with a chain of custom production scripts. Note that the production script is only 5KB, not the development version of 44KB.
    4. Click Live Code in css_support.html (or use the development tool in your browser). Now, as the following illustration shows, there are only three classes to begin with

Reference:

    • Http://www.mhtml5.com/2011/03/676.html
    • Http://www.adobe.com/cn/devnet/dreamweaver/articles/using-modernizr.html
    • Http://zh.wikipedia.org/wiki/Modernizr
    • http://modernizr.com/docs/

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.