async VS defer
defer attributes are boolean attributes that indicate how the script should be evaluated. Classic scripts may specify
async, but must not specify either unless the src attribute is present. Module scripts may specify the
async attribute, but must not specify the
There are several possible modes that can be selected using these attributes, and depending on the script’s type.
For classic scripts, if the
asyncattribute 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
asyncattribute is not present but the
deferattribute 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
asyncattribute 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
deferattribute has no effect on module scripts.)
This is all summarized in the following schematic diagram:
The exact processing details for these attributes are, for mostly historical reasons, somewhat non-trivial, involving a number of aspects of HTML. The implementation requirements are therefore by necessity scattered throughout the specification. The algorithms below (in this section) describe the core of this processing, but these algorithms reference and are referenced by the parsing rules for script start and end tags in HTML, in foreign content, and in XML, the rules for the
document.write() method, the handling of scripting, etc.
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.