The async and defer attributes are boolean attributes that indicate how the script should be evaluated. There are several possible modes that can be selected using these attributes, depending on the script’s type.
async 和 defer 屬性是布爾屬性,它們指示腳本應該如何被評估。可以使用這些屬性選擇幾種可能的模式,具體取決于腳本類型。
For external classic scripts, if the async attribute is present, then the classic script will be fetched in parallel to parsing and evaluated as soon as it is available (potentially before parsing completes). If the async attribute is not present but the defer attribute is present, then the classic script will be fetched in parallel and evaluated when the page has finished parsing. If neither attribute is present, then the script is fetched and evaluated immediately, blocking parsing until these are both complete.
對于外部經典腳本,如果存在 async 屬性,則經典腳本將在解析的同時并行獲取,并在可用時立即評估(可能在解析完成之前)。如果不存在 async 屬性但存在 defer 屬性,則經典腳本將并行獲取,并在頁面解析完成后評估。如果這兩個屬性都不存在,則腳本將立即獲取并評估,阻塞解析直到這些操作都完成。
For module scripts, if the async attribute is present, then the module script and all its dependencies will be fetched in parallel to parsing, and the module script will be evaluated as soon as it is available (potentially before parsing completes). Otherwise, the module script and its dependencies will be fetched in parallel to parsing and evaluated when the page has finished parsing. (The defer attribute has no effect on module scripts.)
對于模塊腳本,如果存在 async 屬性,則模塊腳本及其所有依賴項將在解析的同時并行獲取,模塊腳本將在可用時立即評估(可能在解析完成之前)。否則,模塊腳本及其依賴項將并行獲取,并在頁面解析完成后評估。( defer 屬性對模塊腳本沒有影響。)
This is all summarized in the following schematic diagram:
所有這些內容都總結在下方的示意圖中:
The defer attribute may be specified even if the async attribute is specified, to cause legacy web browsers that only support defer (and not async) to fall back to the defer behavior instead of the blocking behavior that is the default.
即使指定了 async 屬性,也可以指定 defer 屬性,以使僅支持 defer (但不支持 async )的舊版網絡瀏覽器回退到 defer 行為,而不是默認的阻止行為。
參考資料
HTML Standard. https://html.spec.whatwg.org/multipage/scripting.html#attr-script-async