script标签的defer和async区别

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执行前。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • PLEASE READ THE FOLLOWING APPLE DEVELOPER PROGRAM LICENSE...
    念念不忘的阅读 13,562评论 5 6
  • 浏览器中script标签加载顺序是如何的呢?这个问题折腾了好几次了,之前弄清楚了以后,觉得做不做笔记的无关紧要,可...
    世事如烟_f411阅读 1,560评论 0 1
  • NAME dnsmasq - A lightweight DHCP and caching DNS server....
    ximitc阅读 2,936评论 0 0
  • 一切为了组织,我们能到达哪里,能牺牲什么?——《暗算》 看完《听风者》的时候,感受很清楚。阿炳的成功离不开时机,要...
    徐幽默阅读 1,657评论 0 0
  • 最美好的事莫过于天黑躺进暖和的被窝,舒服的让人忘记白天的疲惫。 最期盼的事莫过于我不在,你过的还好!
    千浮生阅读 178评论 0 0