define

Defer: This Boolean property is set to instruct the browser that the script executes after the document has been parsed. Async: Sets this Boolean property to indicate that the browser should execute the script asynchronously if possible.Copy the code
  1. In the case of defer, we can assume that we put the js from the outer chain at the bottom of the page. Loading js does not block page rendering or resource loading. However, defer will be executed in the same order as the original JS, so you can safely use js that have dependencies.

  2. In the case of async, this is a new property in HTML5 that allows scripts to be loaded and executed asynchronously without blocking the page load. In the case of async, js will be executed as soon as it is downloaded, so it may not be executed in the original order. If js has dependencies, async is more likely to fail.

The difference between

Similarities:

  • Does not block page rendering while loading files
  • Not valid for inline scripts
  • The document.write method cannot be called in scripts that use these two properties
  • There are event callbacks to the scripted onload

Difference:

  • The version of HTML, HTML4.0, defined defer; Html5.0 defines async
  • Browser compatibility
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
async attribute (Supported) 3.6 (1.9.2) 10 (Supported)
defer attribute (Supported) 3.5 (1.9.1) 4 (Supported)
  • Execution time Each async script is executed immediately after it finishes downloading and before the Window load event. So it’s possible to get scripts out of order; Each script for the defer property is executed in the original order after the page has been parsed, and before the Document’s DOMContentLoaded.

conclusion

In short, there are three possible scenarios for using these two attributes

  1. If async is true, the script is executed asynchronously after the download is complete.
  2. If async is false and defer is true, the script will execute after the page has been parsed.
  3. If async and defer are both false, the script stops the page parsing in the page parsing, downloads and executes immediately.

Finally, I would like to give some personal advice. Whether to use defer or async attributes, you need to sort out THE JS files in the page first, which files have dependencies among them, which files can be delayed loading, etc. Merge and split THE JS code well, and then use these two attributes according to the needs of the page.