Introduction and use of js library Modernizr
Modernizr is an open-source JS library that makes it easier for designers who develop different levels of experience based on different visitor browsers (referring to differences in support for new standards ).
Traditional browsers will not be completely replaced at present, making it difficult for you to embed the latest CSS3 or HTML5 functions into your website. Modernizr came into being to solve this problem. As an Open Source JavaScript library, Modernizr checks the browser's support for CSS3 or HTML5 functions. Modernizr does not try to add functions not supported by browsers of earlier versions, but allows you to modify the page design by creating optional style configurations. It can also simulate features not supported by browsers of earlier versions by loading custom scripts.
What is Modernizr?
Modernizr is an open source JS library that makes it easier for designers who develop different levels of experience based on different visitor browsers (differences in support of new standards. It allows designers to make full use of HTML5 and CSS3 features in browsers that support HTML5 and CSS3, without sacrificing the control of other browsers that do not support these new technologies.
When you embed a Modernizr script in a webpage, it checks whether the current browser supports the CSS3 feature, for example, @ font-face, border-radius, border-image, box-shadow, rgba, it also checks whether HTML5 features are supported, such as audio, video, local storage, and newThe type and attribute of the tag. You can use these information in browsers that support these features to determine whether to create a JS-based fallback, or you can perform simple and elegant downgrades on unsupported browsers. In addition, Modernizr allows IE to apply CSS styles to HTML5 elements, so that developers can immediately use these more semantic tags.
Modernizr is easy to use, but not omnipotent. The successful use of Modernizr depends largely on your CSS and JavaScript skills.
The main problem with using HTML 5 and CSS 3 is not the difference between popularity and browsers, but the first thing is to understand what these differences are. Once clarified, developers can use the graceful degradation technology to address these limitations. To this end, many developers turned to the open-source project Modernizr.
Instead of checking the user-agent string, Modernizr uses a series of tests to determine the features of the browser. Within several milliseconds, it can perform more than 40 tests and record the results as attributes in an object named Modernizr. Developers can use this information to check whether a feature they are preparing to use is supported by the browser and handle it accordingly.
In Modernizr 2.0, it adds a conditional resource loader for JavaScript and CSS ). The resource loader accepts three parameters. The first is an expression that lists the required features. The second parameter is the list of JavaScript and CSS files loaded if the expression returns true. The third parameter is the list of backup files if the required feature does not exist.
In addition to elegant degradation, the loader can also be used to introduce polyfill. Please allow me to explain to friends who are not familiar with pollyfill that pollyfill is "a JavaScript gasket (shim) that simulates quasi-API for older browsers ". Although this method is not always recommended, pollyfill can be used to add (detected by Modernizr) support for most HTML 5 features. Here, polyfill is used to fill in browser functional vulnerabilities. Sometimes, Modernizr can perform this task seamlessly. However, in essence, this is only a kind of patching work. Therefore, you cannot rely on it to generate completely identical results achieved by a vulnerable browser.
To improve performance, developers can customize Modernizr to perform the tests required for the website. This can be done through the Modernizr download page, which also displays a list of features that can be detected. The github website also displays unmeasurable features and possible solutions.
Modernizr is developed based on the progressive enhancement theory, so it supports and encourages developers to create their websites layer by layer. Everything starts from an idle base where Javascript is applied, and an enhanced application layer is added one by one. Because Modernizr is used, you can easily know what the browser supports.
Principle of Modernizr
Modernizr uses JavaScript to detect the functions supported by the browser. However, it does not dynamically load different style sheets using JavaScript, but uses a very simple technique to add labels for classes to pages. Then, as a designer, you decide to use CSS cascade to provide a proper style for the target element.
For example, if the page supports the box-shadow attribute, Modernizr adds the boxshadow class. If not, use the no-boxshadow class as an alternative.
Because browsers ignore the CSS attributes they cannot recognize, you can safely use the box-shadow attribute according to your basic style rules, however, you need to add a separate descendant selector for the earlier 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 have no-boxshadow class. Therefore, other browsers do not apply this style rule.
The following table lists the class names used by Modernizr to demonstrate support for CSS3. If a function is not supported, the corresponding class name uses no-as the prefix.
CSS Functions |
Modernizr class (attribute) |
@ 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 |
The class name and attribute name are the same no matter where a specific CSS attribute is tested. However, this requires removing any font size or parentheses. Other classes are named based on the CSS3 module they reference.
Use 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 "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 already running. Modernizr does not only do this, but also adds class classes for all features it has detected. If the browser does not support a feature, it adds the "no-" prefix to the class name corresponding to this feature.
Adding 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.
If you use the Live Code of Dreamweaver, you can see that Modernizr has added a large number of classes that indicate the functionality of the browser, as shown in
, No-js class has been replaced by js class, which indicates that JavaScript has been enabled.
If your Dreamweaver version does not have Live Code (or you are using a different HTML editor ), then you can use the development tools provided by most new browsers or the Firebug check generated code provided by the Firefox browser.
3. Use Case 1-display the shadow in a browser that supports shadow and a standard border in an unsupported Browser
Copy the Code as follows:
. Boxshadow # MyContainer {border: none;-webkit-box-shadow: #666 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 element, and then you can manage it to the id of a corresponding div. If not, Modernizr adds the no-boxshadow class to the element, which displays a standard border. In this way, we can easily use the new functions of CSS3 on browsers that support the CSS3 feature, and continue to use the previous methods on browsers that do not support it.
4. Use Case 2-Test 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 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 storag. It is good for developers to develop and test in a multi-version browser.
?
1 2 3 4 5 6 7 8 9 10 |
<Script> window. onload = function () {if (localStorageSupported ()){ Alert ('local storage ororted '); } }; Function localStorageSupported (){ Try {return ('localstore' in window & window ['localstore']! = Null ); } Catch (e ){} Return false; } </Script> |
Unified code
?
1 2 3 4 5 6 7 8 9 |
$ (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 } }); |
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:
?
1 2 3 4 5 6 |
$ (Document). ready (function () {if (Modernizr. borderradius ){ $ ('# MyDiv'). addClass ('borderradiusstyle '); } If (Modernizr.css transforms ){ $ ('# MyDiv'). addClass ('transformsstyle '); } }); |
For audio and video, the returned value is a string, which indicates that the browser can process a specific type of confidence level. According to HTML5 specifications, empty strings indicate that this type is not supported. If this type is supported, the return value is "maybe" or "probably ". For example:
?
1 2 3 |
If (Modernizr. video. h264 = ""){ // H264 is not supported } |
4. Use Case 3 -- use Modernizr to verify the form fields required by HTML5
HTML5 adds many new form attributes, such as autofocus. When a page is loaded for the first time, it automatically places the cursor on a specified field. Another useful property is required. If a required field is left blank, it will prevent HTML5-compatible browsers from submitting forms.
Figure 1. The script detects required fields in browsers that do not support new attributes
Figure 2. The script detects required fields in browsers that do not support new attributes
Before submitting a form, HTML5 compatible browsers will check whether required fields are filled
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
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) {// If autofocus is not supported, the result of this condition is true and inputs [0]. focus () Place 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 generates a function. When a form is submitted, it can traverse all input elements to locate fields with the required attribute. When it finds a field, it removes the leading and trailing spaces from the value. 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 will display a warning related to the missing field name and prevent form submission.
Create a custom version
When you are ready to deploy your website, we recommend that you create a Modernizr Custom production version that only contains the elements you actually need. This reduces the size of the Modernizr library from 44KB to 2KB according to the function you selected. The range of the current options.
For example:
Click http://www.modernizr.com/download/. This opens the interface as shown in.
In CSS3, select box-shadow and CSS columns.
In HTML5 classification, select Input Attributes.
In the Extra category, deselect HTML5 Shim/IEPP.
Make sure the following options in the Extra category are selected (they should have been automatically selected ).
Modernizr. load (yepnope. js)
Add CSS Classes
Modernizr. testProp ()
Modernizr. testAllProps ()
Modernizr. _ domPrefixes
Click Generate.
When the custom script is ready (generally within one to 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 Website. The download page will provide a file name for the production script, such as modernizr. custom.79475.js, but you may want to give it a more meaningful name. In the example file, the name I used is modernizr. adc. js.
Replace the links of modernizr. js in css_support.html and required.html with the links of the Custom production script. Note that the production script is only 5 kb instead of 44KB of the development version.
Click Live Code in css_support.html (or use the development tool in your browser ). As shown in, the start tag has only three classes.