Home > Article > Web Front-end > Summary of how JavaScript solves asynchronous loading implementation methods
By default, javascript is loaded synchronously, that is, javascript is blocked when loading. The subsequent elements must wait for javascript to be loaded before they can be loaded again. For some javascript that is not very meaningful, if it is placed at the head of the page, it will cause If it loads slowly, it will seriously affect the user experience.
(1) defer, only supports IE
Definition and usage of defer attribute
defer attribute specifies whether to delay script execution until the page is loaded.
Some javascript scripts use the document.write method to create the current document content, but other scripts may not.
If your script does not change the content of the document, you can add the defer attribute to the 3f1c4e4b6b16bbbd69b2ee476dc4f83a tag to speed up the processing of the document. Because the browser knows that it will be able to safely read the remainder of the document without executing the script, it will defer interpretation of the script until the document has been displayed to the user.
Example:
<script type="text/javascript" defer="defer"> alert(document.getElementById("p1").firstChild.nodeValue); </script>
(2) async:
The definition and usage of async (it is an attribute of HTML5)
The async attribute specifies that once the script is available, it will be executed asynchronously.
Example:
<script type="text/javascript" src="demo_async.js" async="async"></script>
Note: The async attribute only applies to external scripts (only when using the src attribute).
Note: There are multiple ways to execute external scripts:
•If async="async": the script is executed asynchronously relative to the rest of the page (the script will be executed while the page continues to be parsed)
•If async is not used and defer="defer": the script will be executed when the page completes parsing
•If neither async nor defer is used: the script is read and executed immediately before the browser continues to parse the page
(3) Create script, insert it into DOM, callBack after loading, see code:
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); }
The above is the detailed content of Summary of how JavaScript solves asynchronous loading implementation methods. For more information, please follow other related articles on the PHP Chinese website!