浅谈script中的defer与async属性

背景

个人学习简单记录, 不喜误喷, 有错误麻烦指正, 具体细节直接底部 reference, 感谢.

script

  1. 占据主线程, html parser 处于阻塞状态
  2. 并行下载多个 js 文件
  3. 下载完成后顺序执行

script

script with defer

  1. 与 html parser 同时进行
  2. 并行下载多个 js 文件
  3. DOMContentLoaded事件触发前顺序执行

defer

DOMContentLoaded

MDN 中是这么解释的:

The load event is fired when the whole page has loaded, including all dependent resources such as stylesheets and images. This is in contrast to DOMContentLoaded, which is fired as soon as the page DOM has been loaded, without waiting for resources to finish loading.

也就是说DOMContentLoaded只要 DOM 树解析完成就会触发, 而load事件会继续等待样式,图片等资源解析完毕后触发.

script with async

  1. 与 html parser 同时进行
  2. 并行下载多个 js 文件
  3. 下载完成后阻塞 html parser, 开始执行
  4. 执行不一定是顺序的,所以禁止脚本间存在依赖

async

Summary

  1. 存在多个 js 文件时都会并行下载
  2. defer 与 async 下载 js 与解析 html 同时进行
  3. defer 在DOMContentLoaded触发前执行 js, async 则在下载结束后立即执行
  4. defer 顺序执行 js 文件, async 则先下载完的先执行

reference

async vs defer attributes
浏览器的渲染引擎

negative example

贴一下 google 中找到的反面教材
async 是会影响到页面解析的
彻底搞懂 async & defer


浅谈script中的defer与async属性
https://mariana-yui.github.io/2020/03/14/2020-03-13-async-vs-defer/
作者
Mariana
发布于
2020年3月14日
许可协议