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屬性存在,而後執行這個腳本在頁面完成解析。若是沒有屬性存在,那麼腳本取出並當即執行,在頁面解析完成以前。