【轉】完全搞懂 async & defer

原文地址:https://github.com/xiaoyu2er/blog/issues/8javascript

普通 script

先來看一個普通的 script 標籤。html

<script src="a.js"></script>

瀏覽器會作以下處理java

  • 中止解析 document.
  • 請求 a.js
  • 執行 a.js 中的腳本
  • 繼續解析 document

defer

<script src="d.js" defer></script>
<script src="e.js" defer></script>
  • 不阻止解析 document, 並行下載 d.js, e.js
  • 即便下載完 d.js, e.js 仍繼續解析 document
  • 按照頁面中出現的順序,在其餘同步腳本執行後,DOMContentLoaded 事件前 依次執行 d.js, e.js。

async

<script src="b.js" async></script>
<script src="c.js" async></script>
  • 不阻止解析 document, 並行下載 b.js, c.js
  • 當腳本下載完後當即執行。(二者執行順序不肯定,執行階段不肯定,可能在 DOMContentLoaded 事件前或者後 )

其餘

  • 若是 script 無 src 屬性,則 defer, async 會被忽略
  • 動態添加的 script 標籤隱含 async 屬性

結論

  • 二者都不會阻止 document 的解析
  • defer 會在 DOMContentLoaded 前依次執行 (能夠利用這兩點哦!)
  • async 則是下載完當即執行,不必定是在 DOMContentLoaded 前
  • async 由於順序無關,因此很適合像 Google Analytics 這樣的無依賴腳本

Reference

相關文章
相關標籤/搜索