By default JavaScript is loaded synchronously, that is, JavaScript loading is blocked, after the elements to wait for the JavaScript to be loaded before loading, for some meaning is not very large javascript, if placed in the page header will cause the load is very slow , it can seriously affect the user experience.
(1) Defer, only IE support
Definition and usage of the defer property (I am from the W3school website)
The Defer property specifies whether script execution is deferred until the page is loaded.
Some JavaScript scripts document.write methods to create the current document content, and other scripts are not necessarily.
If your script does not change the contents of the document, you can add the defer attribute to the <script> tag to speed up the processing of the document. Because the browser knows it will be able to safely read the rest of the document without executing the script, it will defer the interpretation of the script until the document has been displayed to the user.
Example:
Copy the code code as follows:
<script type= "Text/javascript" defer= "defer" >
Alert (document.getElementById ("P1"). Firstchild.nodevalue);
</script>
(2) Async:
Definition and usage of async (is the attribute of HTML5)
The async attribute specifies that once the script is available, it executes asynchronously.
Example:
Copy the code code as follows:
<script type= "Text/javascript" src= "Demo_async.js" async= "Async" ></script>
Note: The Async property applies only to external scripts (only when using the SRC attribute).
Note: There are several ways to execute external scripts:
If async= "Async": The script executes asynchronously relative to the rest of the page (the script will be executed when the page resumes parsing)
If Async is not used and defer= "defer": the script executes when the page finishes parsing
If neither async nor defer is used: reads and executes the script immediately before the browser continues to parse the page
(3) Create script, insert into DOM, callback after loading, see code:
Copy the code code as follows:
function Loadscript (URL, callback) {
var script = document.createelement_x ("script")
Script.type = "Text/javascript";
if (script.readystate) {//ie
Script.onreadystatechange = function () {
if (script.readystate = = "Loaded" | |
Script.readystate = = "complete") {
Script.onreadystatechange = null;
Callback ();
}
};
} else {//others:firefox, Safari, Chrome, and Opera
Script.onload = function () {
Callback ();
};
}
script.src = URL;
Document.body.appendChild (script);
}
Three solutions for JS asynchronous loading