Tell me about the difference between defer and async in the script tag?

Reference: Talking about async and defer in the script tag

1. Prerequisite

The script tag is used to load and execute the script. If you use the script directly, the html will load and execute the script in order. During the script loading and execution, the subsequent DOM loading will be blocked.

2、defer

  • If the attribute is set in the script tag, the browser will download the file asynchronously and will not affect subsequent DOM rendering
  • If there are multiple script tags with defer set, all scripts will be executed in order
  • The defer script will be executed after the document is rendered and before the DOMContentLoaded event is called

3、async

  • The setting of async will cause the script to be loaded asynchronously and executed when allowed
  • The execution of async will not be executed in the order of the script in the page, but whoever loads it first will execute

4. Summary

Both async and defer can make script not block DOM rendering. In the process of document parsing, if a common script is encountered, the parsing of the page will be stopped for downloading. Only after parsing the code in the previous script element, will the code in the following <script> element be parsed.
The script with defer will be loaded the day after tomorrow. After the page is parsed and rendered, all defer scripts will be loaded and executed in order . After execution , the DOMContentLoaded event will be triggered.
Scripts with async set will be executed immediately after loading. The current script does not need to wait for other scripts, nor will it block DOM rendering, and there is no guarantee that scripts will be executed in the order in which they appear on the page .

Guess you like

Origin blog.csdn.net/weixin_43912756/article/details/108315891