【HTML】浅谈 script 标签的 defer 和 async
The async and defer attributes are boolean attributes that indicate how the script should be evaluated. There are several possible modes that can be selected using these attributes, depending on the script’s type.
async 和 defer 属性是布尔属性,它们指示脚本应该如何被评估。可以使用这些属性选择几种可能的模式,具体取决于脚本类型。
For external 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.
对于外部经典脚本,如果存在 async 属性,则经典脚本将在解析的同时并行获取,并在可用时立即评估(可能在解析完成之前)。如果不存在 async 属性但存在 defer 属性,则经典脚本将并行获取,并在页面解析完成后评估。如果这两个属性都不存在,则脚本将立即获取并评估,阻塞解析直到这些操作都完成。
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.)
对于模块脚本,如果存在 async 属性,则模块脚本及其所有依赖项将在解析的同时并行获取,模块脚本将在可用时立即评估(可能在解析完成之前)。否则,模块脚本及其依赖项将并行获取,并在页面解析完成后评估。( defer 属性对模块脚本没有影响。)
This is all summarized in the following schematic diagram:
所有这些内容都总结在下方的示意图中:
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.
即使指定了 async 属性,也可以指定 defer 属性,以使仅支持 defer (但不支持 async )的旧版网络浏览器回退到 defer 行为,而不是默认的阻止行为。
参考资料
HTML Standard. https://html.spec.whatwg.org/multipage/scripting.html#attr-script-async