1. HTML5 implements the async attribute of the scriptThis new attribute allows js to be loaded in non-blocking mode in the browser. In addition, the script also has a defer attribute, all browsers have implemented this attribute (except earlier versions of firefox and chrome). IE has done a good job in this aspect and has supported some attributes from the very beginning.
Copy codeThe Code is as follows:
// Async
<Script async src = "dquery. js" async> </script>
// Defer
<Script async src = "dquery. js" defer>
</Script>
2. Differences between async and defer:
Scripts with async or defer will be immediately downloaded and will not block page parsing, and an optional onload event will be provided for processing, which will be called after the script is downloaded, used for initialization related to this script. The difference is that async is executed immediately once the download is complete (in the window. before the onload event), do not ensure the execution order, and defer can ensure that js is executed in the order of its in the page (before the DOMContentLoaded event ).
3. Use the following code to solve browser compatibility problems
Copy codeThe Code is as follows:
Function lazyload (){
Var elem = document. createElement ("script ");
Elem. type = "text/javascript ";
Elem. async = true;
Elem. src = "js/dquery. js? V = 11 "; // corresponding JS File
Document. body. appendChild (elem );
}
If (window. addEventListener ){
Window. addEventListener ("load", lazyload, false );
} Else if (window. attachEvent ){
Window. attachEvent ("onload", lazyload );
} Else {
Window. onload = lazyload ;}
Because it is asynchronously loaded, you need to use the corresponding js content in the window. onload event. A script error will be reported directly on the page, for example: