Original: www.growingwiththeweb.com/2014/02/asy…

The Script tag’s async and defer attributes are currently well supported, so it’s time to take a closer look at how they work.

Illustration shows that

Pure script

First let’s look at the script tag that does not define any attributes. The HTML file is parsed until the script file is clicked, and the parsing stops and a request is made to extract the script file (if external). After the download is complete, the script is executed before resuming parsing.

Set async script

Setting the async property downloads the script file during HTML parsing and pauses the HTML parser to execute the file when the download is complete.

Set the defer script

Setting the defer property will download the script while the HTML is parsed, and execute the file after the HTML is parsed and the script is downloaded. The scripts set as defer will be executed in the order they appear in the document.

Which one should we use?

In general, we’ll use async as much as possible, followed by the defer property, followed by not using it. Here are the general rules of use:

  • Async is used when the script file is independent and modular and does not depend on other script files.
  • If the script depends on or is dependent on another script, use defer;
  • If the script is small and depends on an asynchronous script, use an inline script that does not place any attributes above the asynchronous script.

Compatible with

The DEFER implementation of IE9 and earlier had some terrible errors, so there was no guarantee of execution order. If you need to be compliant with <= IE9, I recommend not using Defer at all, and using the script with no properties set if the execution order is important.