What's the difference between async and defer?

The async and defer are boolean attributes introduced in HTML5 of <script>.

Behavior

neither

1
<script type="text/javascript" src="where.js"></script>

Once the HTML parser meets a <script>, the parser will stop parsing HTML and send a request to get the file (if it’s external). Then, the JavaScript engine will execute the script. After the script’s execution finished, the parser will continue parsing the HTML.

async

1
<script type="text/javascript" src="where.js" async></script>

Once the HTML parser meets a <script async>, the parser won’t stop and the browser will send a request to download the script parallelly. Once the download finishes, the parser will stop parsing HTML if it’s still parsing, and the JavaScript engine will excute the script. After the script’s execution finished, the parser will continue parsing the HTML if there are contents to be parsed.

A typical example, Google Analytics.

BTW, the execution order of async scripts is arbitrary. Once it’s downloaded, it begins to execute. So watch out the location it’s placed.

defer

1
<script type="text/javascript" src="where.js" defer></script>

Once the HTML parser meets a <script defer>, the parser won’t stop and the browser will send a request to download the script parallelly. Even the download finishes, the parser will continue parsing the HTML. After the parser completes parsing the HTML, the JavaScript engine begin to execute the deferred script.

BTW, the deferred scritps are guaranteed to execute in the order they appear in the document.

Both

According to the specification:

The defer attribute may be specified even if the async attribute is specified, to cause legacy Web browsers that only support defer (and not async) to fall back to the defer behavior instead of the synchronous blocking behavior that is the default.

Usage

From my perspective:

  1. The script that do not involve DOM operations and do not rely on other scripts should use async.
  2. The script that contains DOM operations or relies on other scripts upon should use defer.
  3. Small scripts (and relied by async scripts) should just use inline script (and placed before async scripts reling them), which avoid a extra RTT and won’t influence the size of HTML too much.

Compatibility

  1. <= IE9, scripts with defer‘s execution order is not guaranteed. link

References

  1. async vs defer attributes
  2. A picture
  3. script - MDN
Comments