Regular script

In the process of document parsing, if the script is encountered, the page will stop parsing and download (but Chrome will make an optimization, if the script is encountered, it will quickly check whether there are other resources to download, if there are, will download those resources, and then download the corresponding resources of the script. This will save some download time. Resources are downloaded in the parsing process. Although Script1 script will be loaded quickly, script2 in front of it is not loaded & executed, so it can only be in a suspended state, waiting for script2 to be executed after it is executed. When both scripts are finished, the page is parsed.

defer

When the document is parsed, the script with defer set will be downloaded in the background, but the document will not be prevented from rendering, once the page has been parsed & rendered. Wait until all defer scripts are loaded and executed in sequence, and then the DOMContentLoaded event is triggered.

async

The async script is executed after loading. Loading async scripts is not counted in the DOMContentLoaded event statistics, which means that both of the following scenarios are possible

Recommended application scenarios

defer

If your script code depends on the DOM element in the page (whether the document has been parsed), or on other script files. Ex. :

  1. Comment box
  2. Code syntax highlights
  3. polyfill.js

async

If your script doesn’t care about the DOM elements in the page (whether the document has been parsed or not), it won’t generate the data that other scripts need. Ex. :

  1. Baidu statistics

If you’re not sure, defer will always be more stable than Async…