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/Script】fetch
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
相同点:
区别点:
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) |
每个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属性存在,而后执行这个脚本在页面完成解析。若是没有属性存在,那么脚本取出并当即执行,在页面解析完成以前。