Home > Web Front-end > JS Tutorial > Introduction and use of js library Modernizr_Others

Introduction and use of js library Modernizr_Others

WBOY
Release: 2016-05-16 16:00:25
Original
1580 people have browsed it

Traditional browsers will not be completely replaced at this time, making it difficult for you to embed the latest CSS3 or HTML5 features into your website. Modernizr came into being to solve this problem. As an open source JavaScript library, Modernizr detects the browser's support for CSS3 or HTML5 functions. Rather than trying to add features that older browsers don't support, Modernizr lets you modify the page design by creating optional style configurations. It can also load customized scripts to simulate functions that older browsers do not support.

What is Modernizr?

Modernizr is an open source JS library that makes the work of designers who develop different levels of experience based on differences in visitor browsers (referring to differences in support for new standards) easier. It allows designers to make full use of the features of HTML5 and CSS3 in browsers that support and CSS3, while also Controls from other browsers that don't support these new technologies are not sacrificed.

When you embed a Modernizr script in a web page, it will detect whether the current browser supports CSS3 features, such as @font-face, border-radius, border-image, box-shadow, rgba(), etc., and at the same time It will also check whether it supports the

HTML5 features - such as audio, video, local storage, and the new tag types and attributes. Based on obtaining this information, you can use it on browsers that support these features to decide whether to create a JS-based fallback, or simply perform a graceful downgrade for browsers that do not support it. In addition, Modernizr can also enable IE to support applying CSS styles to HTML5 elements, so developers can immediately use these more semantic tags.

Modernizr is simple and easy to use, but it is not omnipotent. Successfully using Modernizr largely depends on your CSS and JavaScript skills. The main issue with using HTML 5 and CSS 3 is not popularity and differences between browsers, but understanding what those differences are in the first place. Once figured out, developers can use graceful degradation techniques to work around these limitations. For this reason, many developers turn to the open source project Modernizr.

Modernizr

Instead of detecting the user-agent string, it uses a series of tests to determine the browser's characteristics. In a few milliseconds it is able to perform over 40 tests and record the results as properties in an object called Modernizr. Developers can use this information to detect whether a feature they plan to use is supported by the browser and handle it accordingly.

In Modernizr

version 2.0 , it adds a conditional resource loader for JavaScript and CSS. The resource loader accepts three parameters, the first of which is an expression enumerating the required features. The second parameter is a list of JavaScript and CSS files to load if the expression returns true. The third parameter is a list of files to fall back on if the required feature is not present. In addition to graceful degradation, loaders can also be used to introduce

polyfills

. Please allow me to explain to those who are not familiar with pollyfill yet. Pollyfill is "a JavaScript shim that emulates the standard API for older browsers." While this approach is not always recommended, pollyfills can be used to add support for most HTML 5 features (detected by Modernizr). Here, polyfills are used to fill holes in browser functionality. Sometimes Modernizr performs this task seamlessly. But at its heart, this is just a patching effort, so it cannot be relied upon to produce the exact same results achieved by a non-vulnerable browser.

To improve performance, developers can customize Modernizr to perform the tests required for their website. This can be done via the Modernizr download page, which also displays a list of features that can be detected. The github website is also marked with undetectable features and possible solutions .

Modernizr is developed based on the theory of progressive enhancement, so it supports and encourages developers to create their websites layer by layer. Everything starts from an empty base with Javascript applied, and enhanced application layers are added one after another. Because you use Modernizr, you can easily know what the browser supports.

The principle of Modernizr

Modernizr uses JavaScript to detect the features supported by the browser. However, instead of using JavaScript to dynamically load different stylesheets, it uses a very simple technique of adding classes to the tag of the page. It is then up to you as the designer to provide the appropriate styling for the target element using CSS cascading.

For example, if the page supports the box-shadow property, Modernizr will add the boxshadow class. If it is not supported, then it is added using the no-boxshadow class as an alternative.

Since browsers ignore CSS properties they don’t recognize, you can safely use the box-shadow property according to your basic styling rules, however you will need to add a separate descendant in the format below for older browsers selector

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

Only browsers that do not support box-shadow will have the no-boxshadow class, 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 Functions

Modernizr class (property)

@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

No matter where a specific CSS property is tested, the class name and property name will be the same, however this requires removing any hyphens or parentheses. Other classes are named after the CSS3 modules they reference.

Usage of Modernizr

1. Download

First download the latest stable version of Modernizr from www.modernizr.com. Add it to the area of ​​the page:

2. Add the "no-js" class to the element

When Modernizr is running, it will change the "no-js" class to "js" to let you know that it is running. Modernizr not only does this, it also adds classes to all the features it detects. If the browser does not support a feature, it adds "no-" to the class name corresponding to the feature. prefix.
Adding no-js class to the html element tells the browser whether it supports JavaScript. If it does not support JavaScript, it will display no-js. If it supports it, delete no-js
At this point, if you use Dreamweaver’s Live Code, you can see that Modernizr has added a large number of classes indicating browser functions, as shown below

As shown in the picture, the no-js class has been replaced by the js class, which indicates that JavaScript has been enabled.

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

3. Use case 1 - Display shadow in browsers that support shadow shadow, and display standard borders in browsers that do not support it

Copy code The code is 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 the boxshadow class to the element, and then you can manage it to the id of a corresponding div. If it is not supported, Modernizr will add the no-boxshadow class to the element so that a standard border is displayed. In this way, we can easily use new CSS3 features on browsers that support CSS3 features, and continue to use the previous methods on browsers that do not support them.

4. Use case 2 - testing local storage

In addition to adding the corresponding class to the element, Modernizr also provides a global Modernizr JavaScript object, which provides different attributes to indicate whether a certain new feature is supported by 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 multiple versions of browsers.

<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> 
Copy after login

Everyone 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 is not supported
  
 }
});
Copy after login

The global Modernizr object can also be used to detect whether CSS3 features are 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');
 }
}); 
Copy after login

For audio and video, the return value is a string indicating the confidence level that the browser can handle the specific type. 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
}
Copy after login

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

HTML5 adds many new form attributes, such as autofocus, which automatically places the cursor in a specified field when the page first loads. Another useful attribute is required, which will prevent HTML5-compliant browsers from submitting the form if a required field is left blank.

Figure 1. Script detects required fields in browsers that do not support the new attribute

Figure 2. Script detects required fields in browsers that do not support the new attribute

Before submitting the form, HTML5-compatible browsers will check whether required fields are filled in

window.onload = function() { // get the form and its input elements   var form = document.forms[0], inputs = form.elements; // if no autofocus, put the focus in the first field   if (!Modernizr.input.autofocus) { //因如果不支持 autofocus,那么该条件的求值结果为 true,并且 inputs[0].focus() 将光标放在第一个输入字段      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; 
    } 
  };
 } 
}
Copy after login

The code generates a function that iterates through all input elements when the form is submitted in order to find fields with the required attribute. When it finds a field, it removes leading and trailing whitespace from the value, and if the result is an empty string, it adds the result to the required array. After all fields have been checked, if the array contains certain elements, the browser displays a warning about missing field names and prevents the form from being submitted.

Create a custom version

When you are ready to deploy your website, it is recommended to create a custom production version of Modernizr that contains only those elements you actually need. This reduces the size of the Modernizr library from 44KB to 2KB based on your selected features. The current range of options is shown in the figure.

For example:

  1. Click http://www.modernizr.com/download/. This will open the interface shown above.
  2. In the CSS3 category, select box-shadow and CSS columns.
  3. In the HTML5 category, select Input Attributes.
  4. In the Extra category, deselect HTML5 Shim/IEPP.
  5. Make sure the following options are selected in the Extra category (they should be selected automatically).
    • 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 (usually within one to two seconds), a Download button will appear next to the Generate button. Click the Download button and save the file in the js folder of the sample website. The download page will give the production script a filename, such as modernizr.custom.79475.js, but you may want to give it a more meaningful name. In the sample file, I used the name modernizr.adc.js.
  3. Replace the links to modernizr.js in css_support.html and required.html with links to your custom production script. Note that the production script is only 5KB, not the 44KB of the development version.
  4. Click Live Code in css_support.html (or use the development tool in your browser). Now, as shown below, the opening tag only has three classes.

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/
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template