script标签属性async和defer的区别

1.async: 表示应该当即下载脚本,但不该妨碍页面中的其余操做,好比下载其余资源或html

等待加载其余脚本。只对外部脚本文件有效。html5

async的含义【摘自https://developer.mozilla.org/En/HTML/Element/Script浏览器

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

2.defer:表示脚本能够延迟到文档彻底被解析和显示以后在执行。只对外部脚本文件有效。 全部元素解析完成以后,DOMContentLoaded 事件触发以前完成。async

defer的含义【摘自https://developer.mozilla.org/En/HTML/Element/Scriptfetch

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

相同点与区别:spa

  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.code

  总结以下:orm

相同点:

  • 加载文件时不阻塞页面渲染
  • 对于inline的script无效
  • 使用这两个属性的脚本中不能调用document.write方法
  • 有脚本的onload的事件回调

区别点:

  • html的版本html4.0中定义了defer;html5.0中定义了async
  • 浏览器
    Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
    Basic support 1.0 1.0 (1.7 or earlier) (Supported) (Supported) (Supported)
    async attribute (Supported) 3.6 (1.9.2) 10 (Supported)
    defer attribute (Supported) 3.5 (1.9.1) 4 (Supported)
  • 执行时刻
    每个async属性的脚本都在它下载结束以后马上执行,同时会在window的load事件以前执行。因此就有可能出现脚本执行顺序被打乱的状况;

   每个defer属性的脚本都是在页面解析完毕以后,按照本来的顺序执行,同时会在document的DOMContentLoaded以前执行。

摘自【http://dev.w3.org/html5/spec/Overview.html#attr-script-async】。

  There are three possible modes that can be selected using these attributes. If the async attribute is present,then the script will be executed asynchronously, as soon as it is available. If the async attribute is not present but the defer attribute is present, then the script is executed when the page has finished parsing. If neither attribute is present, then the script is fetched and executed immediately, before the user agent continues parsing the page.

  这些属性被选择使用,有三种可能的模式。若是async属性存在,只要被加载完成,那么脚本将异步执行的。若是async属性不存在但defer属性存在,而后执行这个脚本在页面完成解析。若是没有属性存在,那么脚本取出并当即执行,在页面解析完成以前。

相关文章
相关标签/搜索