In general, JavaScript scripts are generally recommended to be placed at the bottom of the body tag, because using the script tag to load JS, will stop loading the subsequent content and stop to parse the script and render the page, using the SRC attribute to load external scripts will also cause such a situation, so, If you put too many script tags in front of head or body, and a lot of content, it will cause the page to parse all the script tags before the content of a short time the entire page blank, to the user experience will be very poor. However, if all the scripts are placed at the bottom, it will cause the DOM to be loaded after a while, but the interaction with the user is poor, so some scripts and pages need to be loaded asynchronously.
1. In HTML5, script adds an async attribute that, after the script has been added, can be downloaded in parallel with the rest of the page, but the property must be available in browsers above IE9 and can only be used to load external JS scripts.
2. Similarly, there is a defer attribute in Html4, which is a bit more compatible, but as with async, the JS script can be loaded asynchronously and can only be used to load external JS scripts.
The difference between the ASYC and defer properties is that async causes the script to execute as soon as it is loaded, and the defer script executes after the DOM is loaded. The execution of the defer script is preceded by the window.onload, and other scripts that do not have the defer attribute added.
<!DOCTYPE HTML><HTMLLang= "en"><Head> <title></title> <MetaCharSet= "UTF-8"></Head><Script>window.onload= function() {Console.log ("window.onload"); }</Script><Scriptsrc= "Js/defer.js"defer></Script><Script>Console.log ("Normal");</Script><Body></Body></HTML>
The order of display is: normal defer window.onload
3. Use XHR to load JS content asynchronously and execute the code as follows
<!DOCTYPE HTML><HTMLLang= "en"><Head> <title></title> <MetaCharSet= "UTF-8"></Head><Script> varXHR= NewXMLHttpRequest (); Xhr.open ("Get", "Js/defer.js", True) Xhr.send (); Xhr.onreadystatechange= function() { if(Xhr.readystate== 4 &&Xhr.status== $) {eval (xhr.responsetext); } }</Script><Body></Body></HTML>
4. Dynamically create the script tag, the main code is as follows
var script = document.createelement ("script"); = "Js/test.js"; Document.head.appendChild (script);
This method can also monitor the state of the load through the script's onreadystate.
5.iframe mode, the use of an IFRAME to load a homologous sub-page, so that the sub-page JS affect the current parent page a way.
Several ways to load JavaScript scripts asynchronously