script标签属性async和defer的区别
1.async: 表示应该立即下载脚本,但不应妨碍页面中的其他操作,比如下载其他资源或
等待加载其他脚本。只对外部脚本文件有效。
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 事件触发之前完成。
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.
相同点与区别:
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.
总结如下:
相同点:
- 加载文件时不阻塞页面渲染
- 对于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) asyncattribute(Supported) 3.6 (1.9.2) 10 — (Supported) deferattribute(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属性存在,然后执行这个脚本在页面完成解析。如果没有属性存在,那么脚本取出并立即执行,在页面解析完成之前。

浙公网安备 33010602011771号