Skip to content

Instantly share code, notes, and snippets.

@zxhfighter
Created February 26, 2018 02:44
Show Gist options
  • Save zxhfighter/bb92db1cdb7243ebc3aadfece24d86df to your computer and use it in GitHub Desktop.
Save zxhfighter/bb92db1cdb7243ebc3aadfece24d86df to your computer and use it in GitHub Desktop.
the difference of the async and defer

async and defer

TL;DR

defer 和 async 的区别是:

  1. defer 是渲染完再执行,async 是下载完就执行;
  2. 如果有多个 defer 会按照页面出现顺序执行,而 async 则不会;
  3. 如果 defer 和 async 都出现,会优先采用 async 规则,如果不支持 async 指令,则会 fallback 到 defer 指令

The async and defer attributes are boolean attributes that indicate how the script should be executed. Classic scripts may specify defer or async; module scripts may specify async.

There are several possible modes that can be selected using these attributes, and depending on the script’s type.

For classic scripts, if the async attribute is present, then the classic script will be fetched in parallel to parsing and evaluated as soon as it is available (potentially before parsing completes). If the async attribute is not present but the defer attribute is present, then the classic script will be fetched in parallel and evaluated when the page has finished parsing. If neither attribute is present, then the script is fetched and evaluated immediately, blocking parsing until these are both complete.

For module scripts, if the async attribute is present, then the module script and all its dependencies will be fetched in parallel to parsing, and the module script will be evaluated as soon as it is available (potentially before parsing completes). Otherwise, the module script and its dependencies will be fetched in parallel to parsing and evaluated when the page has finished parsing. (The defer attribute has no effect on module scripts.)

This is all summarized in the following schematic diagram:

asyncdefer

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 blocking behavior that is the default.

see more on https://www.w3.org/TR/html52/semantics-scripting.html#element-attrdef-script-async

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment