Machine Morning

機械学習やWebについて学んだことを記録しています。

DOMContentLoadedとload

document.addEventListener("DOMContentLoaded", event => {
    console.log("DOM fully loaded and parsed");
});

window.addEventListener("load", event => {
    console.log("All resources finished loading");
});

console.log("script.js finished loading till the end");

script.jsとして実行すると、

script.js finished loading till the end
DOM fully loaded and parsed
All resources finished loading

の結果を得る。 通常のconsole.log("");はその場で実行され、DOMContentLoadedはDOMツリーの構築が完了した時点で発火される。loadはDOMツリーに加えて、画像などのすべてのリソース、スクリプト、ファイルが読み込まれた時点で発火するので、DOMContentLoadedの発火よりも後になる。

ちなみに、DOMContentLoadedはdocumentオブジェクト、loadはwindowオブジェクトに存在する。

asyncとdefer

script.jsに加え、script2.jsとscript3.jsを用意する。

console.log("script2.js finished loading till the end");

script2.js

console.log("script3.js finished loading till the end");

script3.jsとして

<script src="./script.js"></script>
<script src="./script2.js"></script>
<script src="./script3.js"></script>

index.htmlで順番に読み込む。

script.js finished loading till the end
script2.js finished loading till the end
script3.js finished loading till the end
DOM fully loaded and parsed
All resources finished loading

するとこのようにaddEventListenerで追加したDOMContentLoadedとload以外は読み込まれた順番に実行される。

<script src="./script.js"></script>
<script src="./script2.js" async></script>
<script src="./script3.js"></script>

script2.jsの読み込みに属性asyncを追加すると、

script.js finished loading till the end
script3.js finished loading till the end
DOM fully loaded and parsed
script2.js finished loading till the end
All resources finished loading

というようにscript2.jsのスクリプトは非同期でダウンロードされ、同時にHTMLのパースが並行して行われる。 今回は、DOMの構築が先に終了したため、script2.jsの実行が後となった。