JS下載解析時(shí)候會(huì)阻塞DOM樹的構(gòu)建运敢,放在HTML頂部 的時(shí)候會(huì)有可能出現(xiàn)長時(shí)間白屏的情況校仑,想讓JS解析時(shí)候阻塞DOM樹構(gòu)建的話必定會(huì)談到defer和async兩個(gè)屬性,兩個(gè)究竟是什么和有什么區(qū)別呢传惠?
1迄沫、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.
defer這一布爾屬性是告訴瀏覽器這個(gè)script標(biāo)簽需要在文檔解析完成后再去執(zhí)行
2、async[HTML5] ?[https://developer.mozilla.org/En/HTML/Element/Script]
Set this Boolean attribute to indicate that the browser should, if possible, execute the script asynchronously.
async這一布爾屬性告訴瀏覽器在可能得情況下異步執(zhí)行script標(biāo)簽
Difference
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.
async 和 defer的script標(biāo)簽在開始下載時(shí)候都不會(huì)暫停解析阻塞頁面和提供onload時(shí)候的回調(diào)卦方。async屬性的腳本會(huì)在下載結(jié)束后立即執(zhí)行羊瘩,同時(shí)也會(huì)在window的load時(shí)間前執(zhí)行,所以有可能會(huì)出現(xiàn)腳本執(zhí)行順序被打亂的情況。相反的尘吗,defer則保證了腳本能順序執(zhí)行逝她,其執(zhí)行時(shí)間會(huì)在頁面解析完成后,同時(shí)也在DOMContentLoaded執(zhí)行前睬捶。