The async
and defer
are boolean attributes introduced in HTML5 of <script>
.
Behavior
neither
|
|
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
|
|
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
|
|
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:
- The script that do not involve DOM operations and do not rely on other scripts should use
async
. - The script that contains DOM operations or relies on other scripts upon should use
defer
. - Small scripts (and relied by
async
scripts) should just useinline
script (and placed beforeasync
scripts reling them), which avoid a extra RTT and won’t influence the size of HTML too much.
Compatibility
- <= IE9, scripts with
defer
‘s execution order is not guaranteed. link