This is the sixth day of my participation in the August More text Challenge. For details, see: August More Text Challenge

We know that the rendering engine will stop when encountering the script tag and wait for the script to be loaded and executed before continuing to render. This traditional JS loading method has obvious shortcomings. When too much JS load, will seriously affect the page rendering efficiency, once the network speed is not good, then the whole site will be waiting, waiting for the JS load execution, instead of subsequent rendering work. Sometimes when loading the tool method, we want to load without blocking the rendering of the page; Sometimes there are tools that load on demand and then load when needed. This is where asynchronous loading is needed

There are three ways to load JavaScript asynchronously

1. Defer load asynchronously (IE available)

<! 1 - - - >
<script defer = "defer" src = "./index.js"></script>
<! -- -- -- > 2
<script defer = "defer">
  //code
</script>
Copy the code

Defer: Load as encountered, but wait until the DOM document is fully parsed before being executed

2. Async Asynchronous loading

<script async = "async" src = "./index.js"></script>
Copy the code

Async: meet load, loading the execution, not to consider whether the DOM parsing out! Async can only load external JS asynchronously. It cannot write JS code inside script tags. Let async load js code inside asynchronously.

You can use async and defer at the same time, so that both Internet Explorer 4 and other browsers support asynchronous loading

<script  src = "./js/tools.js"  async  defer></script>
Copy the code

3. Manual encapsulation and on-demand loading

Manually encapsulate a method and call it where needed

// Manually encapsulate the method of loading js asynchronously
function asyncLoadScript(url, callback) {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  if (script.readyState) {//readyState is the status code in IE
    script.onreadystatechange = function () {
      // Bind the event of the listener status code. If the IE status code becomes complete or loaded, the element is loaded
      if (script.readyState == "complete" || script.readyState == "loaded") {
        callback();// The callback function is called when the script is loaded}}}else {
    // Non-IE uses the onLoad event to indicate when the script has been loaded
    script.onload = function () {
      callback();// The callback function is called when the script is loaded
    }
  }
  script.src = url;Onreadystatechange = onreadyStatechange = onReadyStatechange = onReadyStatechange
  document.head.appendChild(script);// Load into the page
}
/ / execution
asyncLoadScript('./js/tools.js'.function () {
  //code
  console.log('Loaded according to:' + url + 'file')});Copy the code