浅谈script中的defer与async属性
背景
个人学习简单记录, 不喜误喷, 有错误麻烦指正, 具体细节直接底部 reference, 感谢.
script
- 占据主线程, html parser 处于阻塞状态
- 并行下载多个 js 文件
- 下载完成后顺序执行
script with defer
- 与 html parser 同时进行
- 并行下载多个 js 文件
DOMContentLoaded
事件触发前顺序执行
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 toDOMContentLoaded
, 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
- 与 html parser 同时进行
- 并行下载多个 js 文件
- 下载完成后阻塞 html parser, 开始执行
- 执行不一定是顺序的,所以禁止脚本间存在依赖
Summary
- 存在多个 js 文件时都会并行下载
- defer 与 async 下载 js 与解析 html 同时进行
- defer 在
DOMContentLoaded
触发前执行 js, async 则在下载结束后立即执行 - 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/