The following three types of scripts are encountered in HTML:

  • <script src='xxx'></script>
  • <script src='xxx' async></script>
  • <script src='xxx' defer></script>

So what’s the difference between the three types of script?

script

When the browser parses HTML, if it encounters a script tag with no attributes, it will pause parsing, first send a network request to get the code content of the JS script, then let the JS engine execute the code, and resume parsing when the code is finished. The whole process is shown in the figure below:

As you can see, the script blocks the browser’s parsing of the HTML. If a network request for a JS script is delayed, or the EXECUTION of the JS script takes too long, a white screen will result, and the user will not see the content of the page.

async script

Async indicates asynchronous, such as seven cattle source there are a large number of async appear:

When the browser runs into a script with the async property, the network request for the script is asynchronous and does not block the browser from parsing the HTML. Once the network request comes back, if the HTML has not been parsed by this time, the browser will pause parsing and let the JS engine execute the code. The picture is as follows:

Of course, if the HTML has been parsed before the JS request comes back, then nothing will happen and the JS code will be executed immediately, as shown in the figure below:

So async is not controllable, because the execution time is uncertain, if you get a DOM element in an asynchronous JS script, you may or may not get it. Moreover, if there are multiple async, the order of execution between them is also uncertain, and it completely depends on the network transmission results, who is the first to execute who.

defer script

Defer indicates delay, for example, there was a lot of defer in the mining source:

When the browser encounters the script with the defer property, the network request to get the script is also asynchronous and will not block the browser from parsing the HTML. Once the network request comes back, the browser will not pause parsing and execute the JS code if the HTML has not been parsed yet. Instead, wait until the HTML is parsed before executing the JS code, as shown below:

If there are multiple Defer Script tags, the browser (except IE9 and below) will ensure that they are executed in the order they appear in the HTML without breaking any dependencies between the JS scripts.

Finally, based on the above analysis, the execution order of different types of script and whether they block parsing HTML is summarized as follows:

The script tag JS execution order Whether to block parsed HTML
<script> Order in HTML blocking
<script async> Network request return order It may or may not block
<script defer> Order in HTML Don’t block