Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

script标签的async和defer的区别 #7

Open
wanCheng7 opened this issue Dec 2, 2019 · 0 comments
Open

script标签的async和defer的区别 #7

wanCheng7 opened this issue Dec 2, 2019 · 0 comments

Comments

@wanCheng7
Copy link
Owner

wanCheng7 commented Dec 2, 2019

解析过程

不加async和defer的script标签
html文档加载过程中遇到了<script>标签,会停止html的渲染,然后开始加载<script>内容并执行。所以页面会出现短暂的卡顿或白屏。

async
asynctrue时,会异步加载js文件,等文件加载完毕之后立即执行,在执行过程中还是会阻塞html文档的渲染。

defer
defertrue时,同样会异步加载js文件,但是并不会马上执行,而是会等html文档渲染完之后才执行,作用有点类似于把<script>标签放在<body>下面。

区别

引用一张网上的加载示意图:
image

从图中可以很清晰地看出asyncdefer的区别,他们都是异步加载的js文件,能够一定程度上减少页面渲染的阻塞时间,不同点就是js执行的时间点不一样。而且,当多个<script>标签都加了defer标签时,会按照先后顺序执行,而多个<script>标签都加了async标签时不一定会按顺序执行,因为是根据加载时间决定的。所以,对于有依赖关系的js文件,async加载方式可能会出问题。

参考

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant