Find 6 on the Internet, if there are others welcome to add
1. The defer attribute
HTML 4.01 defines the defer attribute for the
Purpose: Indicates that script execution does not affect page construction. That is, the script is delayed until the entire page has been parsed.
Setting the defer attribute in the
<! DOCTYPE html> <html> <head> <script src="test1.js" defer="defer"></script> <script src="test2.js" defer="defer"></script> </head> <body> <! </body> </ HTML >Copy the code
Although the
The HTML5 specification requires scripts to be executed in the order in which they appear. In reality, deferred scripts are not always executed sequentially.
The defer attribute applies only to external script files. An HTML5-enabled implementation ignores the defer attribute embedded in the script Settings
2.Async attributes
HTML5 defines async properties for
The asynchronous script must be executed before the page load event. There is no guarantee that the scripts will be executed in order.
<! DOCTYPE html> <html> <head> <script src="test1.js" async></script> <script src="test2.js" async></script> </head> <body> <! </body> </ HTML >Copy the code
Async, like defer, does not block other resource downloads, so it does not affect page loading.
Disadvantages: can’t control the loading order
3. Create the DOM dynamically
// These codes should be placed before the </body> tag (near the bottom of the HTML file) <script type="text/javascript"> function downloadJSAtOnload() {varelement = document.createElement("script"); element.src = "defer.js"; document.body.appendChild(element); } if (window.addEventListener) window.addEventListener("load",downloadJSAtOnload, false); else if (window.attachEvent) window.attachEvent("onload",downloadJSAtOnload); else window.onload =downloadJSAtOnload; </script>Copy the code
4. Use jQuery’s getScript() method
$.getscript ("outer. Js ",function(){console.log(" script loaded ")});Copy the code
5. UsesetTimeout
Delay method
6. Let JS load last
To speed up the page load, place the file imported from outside js at the bottom of the page so that JS is imported last