Differences between async and defer attributes in script tags of interview questions

Time:2021-1-22

Differences between async and defer attributes in script tags of interview questions

Original reading

Recently, I’ve been doing some things about web page performance optimization. After running lighthouse, a performance testing tool of chrome devtools, I found that one of them isEfficiently load third-party JavaScript, which is the third-party library that we refer to with script tag in our project.

First of all, we should write the script tag in the body, so that the browser will not parse JS when loading HTML documents, which will prevent HTML rendering.

How to optimize the loading of third party scripts?

One way is to addasyncperhapsdeferProperty.

like this:

<script async>

<script defer>

async

The async attribute is executed after the script is downloaded and before the load event of window. If the documents are not parsed at this time, it means that they can prevent DOM construction.

Differences between async and defer attributes in script tags of interview questions

defer

The defer attribute is executed after the document is fully parsed, before the domcontentloaded event in the window. The defer property ensures that they are executed in the order in which they appear in HTML, and does not prevent the main thread from rendering.

Differences between async and defer attributes in script tags of interview questions

  • This script can be used if it needs to be executed early in the loading processasync
  • If this script is not that important, it can be useddefer

reference material
efficiently-load-third-party-javascript