Make a summary every day, persistence is victory!

/** @date 2021-05-22 @description script tag defer defer attribute and async attribute difference */Copy the code

One (sequence)

When the browser encounters a script tag, it stops rendering and starts executing the script. If it is an external script, it needs to download it and wait for the script to complete and then start rendering down again. If the script takes too long to download and execute, the browser will block, which is undoubtedly a bad user experience. Therefore, the browser allows the script tag to load the script asynchronously. Defer and Async are the two asynchronous loading methods. When the browser encounters a Script tag with defer or async attributes, it starts downloading the script, but instead of waiting for the download and execution to complete, it executes the subsequent code.

Ii (Use)

To load the script asynchronously, open the defer or async properties in the Script tag:

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

Three (Difference)

Defer differs from the Async attribute in the following two ways:

  1. The asynchronous load tag using the defer attribute is executed after the browser has rendered, while async is executed immediately after downloading;
  2. Multiple tags that enable the defer attribute guarantee the load order, while async does not;

Iv (Extended)

As mentioned above, the script download time is too long, which will cause browser block, which will cause the page blank screen problem; Try to place the script tag after the body tag to avoid blocking.