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脚本执行顺序之defer、async #42

Open
zhuzhh opened this issue Apr 8, 2020 · 0 comments
Open

script脚本执行顺序之defer、async #42

zhuzhh opened this issue Apr 8, 2020 · 0 comments

Comments

@zhuzhh
Copy link
Owner

zhuzhh commented Apr 8, 2020

defer特性是html4规范定义的新特性;表示脚本下载完毕不会立即实现,而是等到页面解析完毕之后在执行

在defer的脚本中,如果存在dociment.write代码,这个脚本不会产生任何文档内容

MDN解释:defer的脚本不会阻塞页面的解析,而是等到页面解析结束之后再执行;defer的脚本依然是在DOMContentLoaded事件之前执行的,因此它还是会阻塞DOMContentLoaded中的脚本。

兼容性:支持到ie10

image

总的来看,defer的作用一定程度上与将脚本放置在页面底部有一定的相似;多个脚本使用defer,则会按照顺序执行

async特性是HTML5中引入的特性

async指异步加载而不是异步执行;一旦加载完毕就会执行代码,而执行的过程肯定还是同步的,也就是阻塞的。

async脚本的执行时机是无法确定的,因为脚本何时加载完毕也是不确定的。

async兼容情况: 兼容到ie10

image

async优先级大于defer

手动实现async,和实现jsonp类似

script.onreadystatechange = function(){
    if(script.readyState === "loaded" || script.readyState === "complete"){
        callback&&callback();
    }
 }
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