美文网首页
script标签的defer和async区别

script标签的defer和async区别

作者: kitssang | 来源:发表于2017-01-22 18:42 被阅读0次

    JS下载解析时候会阻塞DOM树的构建,放在HTML顶部 的时候会有可能出现长时间白屏的情况,想让JS解析时候阻塞DOM树构建的话必定会谈到defer和async两个属性,两个究竟是什么和有什么区别呢?

    1、defer [https://developer.mozilla.org/En/HTML/Element/Script]

    This Boolean attribute is set to indicate to a browser that the script is meant to be executed after the document has been parsed.

    defer这一布尔属性是告诉浏览器这个script标签需要在文档解析完成后再去执行

    2、async[HTML5]  [https://developer.mozilla.org/En/HTML/Element/Script]

    Set this Boolean attribute to indicate that the browser should, if possible, execute the script asynchronously.

    async这一布尔属性告诉浏览器在可能得情况下异步执行script标签

    Difference

    Both async and defer scripts begin to download immediately without pausing the parser and both support an optional onload handler to address the common need to perform initialization which depends on the script. The difference between async and defer centers around when the script is executed. Each async script executes at the first opportunity after it is finished downloading and before the window’s load event. This means it’s possible (and likely) that async scripts are not executed in the order in which they occur in the page. The defer scripts, on the other hand, are guaranteed to be executed in the order they occur in the page. That execution starts after parsing is completely finished, but before the document’s DOMContentLoaded event.

    async 和 defer的script标签在开始下载时候都不会暂停解析阻塞页面和提供onload时候的回调。async属性的脚本会在下载结束后立即执行,同时也会在window的load时间前执行,所以有可能会出现脚本执行顺序被打乱的情况。相反的,defer则保证了脚本能顺序执行,其执行时间会在页面解析完成后,同时也在DOMContentLoaded执行前。

    相关文章

      网友评论

          本文标题:script标签的defer和async区别

          本文链接:https://www.haomeiwen.com/subject/glhobttx.html