默認(rèn)方式
瀏覽器會(huì)并行加載script, 但是執(zhí)行是書(shū)寫(xiě)的順序旗们,如果script1執(zhí)行未完畢,就不會(huì)開(kāi)始執(zhí)行script2,盡管script2已經(jīng)加載完缘眶。
而且這種方式會(huì)阻礙script標(biāo)簽后面其他元素的渲染抠蚣,直到script1執(zhí)行完畢才會(huì)渲染后面的dom
<script src='./script1.js'></script>
<div>after scrpit1</div>
<script src='./script2.js'></script>
<div>after scrpit2</div>
async方式
這種方式不會(huì)阻礙script標(biāo)簽后面其他元素的渲染网梢,誰(shuí)加載快誰(shuí)先執(zhí)行
<script async src='./script1.js'></script>
<div>after scrpit1</div>
<script async src='./script2.js'></script>
<div>after scrpit2</div>
- 測(cè)試用例:使用node服務(wù),將script1請(qǐng)求的響應(yīng)時(shí)間控制比script2長(zhǎng)
- 測(cè)試結(jié)果:
1. script2開(kāi)始執(zhí)行 1576223742526
2. script2執(zhí)行完畢 1576223744794
3. script1開(kāi)始執(zhí)行 1576223744795
4. script1開(kāi)始執(zhí)行 1576223747009
defer方式
這種方式不會(huì)阻礙script標(biāo)簽后面其他元素的渲染嚣伐,會(huì)按照書(shū)寫(xiě)書(shū)序執(zhí)行.
<script defer src='./script1.js'></script>
<div>after scrpit1</div>
<script defer src='./script2.js'></script>
<div>after scrpit2</div>
- 測(cè)試用例:使用node服務(wù)糖赔,將script1請(qǐng)求的響應(yīng)時(shí)間控制比script2長(zhǎng)
- 測(cè)試結(jié)果:
1. script1開(kāi)始執(zhí)行 1576224918596
2. script1開(kāi)始執(zhí)行 1576224920828
3. script2開(kāi)始執(zhí)行 1576224920829
4. script2執(zhí)行完畢 1576224923093