In below snippet I collect choosen methods and show their sequence. Remarks
document.onload
(X) is not supported by any modern browser (event is never fired)<body onload="bodyOnLoad()">
(F) and at the same time window.onload
(E) then only first one will be executed (because it override second one)<body onload="...">
(F) is wrapped by additional onload
functiondocument.onreadystatechange
(D) not override document .addEventListener('readystatechange'...)
(C) probably cecasue onXYZevent-like
methods are independent than addEventListener
queues (which allows add multiple listeners). Probably nothing happens between execution this two handlers.div
write their timestamps also in body (click "Full Page" link after script execution to see it).readystatechange
(C,D) are executed multiple times by browser but for different document states:
DOMContentLoaded
body/window onload
<html>_x000D_
_x000D_
<head>_x000D_
<script>_x000D_
// solution A_x000D_
console.log(`[timestamp: ${Date.now()}] A: Head script`);_x000D_
_x000D_
// solution B_x000D_
document.addEventListener("DOMContentLoaded", () => {_x000D_
print(`[timestamp: ${Date.now()}] B: DOMContentLoaded`);_x000D_
});_x000D_
_x000D_
// solution C_x000D_
document.addEventListener('readystatechange', () => {_x000D_
print(`[timestamp: ${Date.now()}] C: ReadyState: ${document.readyState}`);_x000D_
});_x000D_
_x000D_
// solution D_x000D_
document.onreadystatechange = s=> {print(`[timestamp: ${Date.now()}] D: document.onreadystatechange ReadyState: ${document.readyState}`)};_x000D_
_x000D_
// solution E (never executed)_x000D_
window.onload = () => {_x000D_
print(`E: <body onload="..."> override this handler`);_x000D_
};_x000D_
_x000D_
// solution F_x000D_
function bodyOnLoad() {_x000D_
print(`[timestamp: ${Date.now()}] F: <body onload='...'>`); _x000D_
infoAboutOnLoad(); // additional info_x000D_
}_x000D_
_x000D_
// solution X_x000D_
document.onload = () => {print(`document.onload is never fired`)};_x000D_
_x000D_
_x000D_
_x000D_
// HELPERS_x000D_
_x000D_
function print(txt) { _x000D_
console.log(txt);_x000D_
if(mydiv) mydiv.innerHTML += txt.replace('<','<').replace('>','>') + '<br>';_x000D_
}_x000D_
_x000D_
function infoAboutOnLoad() {_x000D_
console.log("window.onload (after override):", (''+document.body.onload).replace(/\s+/g,' '));_x000D_
console.log(`body.onload==window.onload --> ${document.body.onload==window.onload}`);_x000D_
}_x000D_
_x000D_
console.log("window.onload (before override):", (''+document.body.onload).replace(/\s+/g,' '));_x000D_
_x000D_
</script>_x000D_
</head>_x000D_
_x000D_
<body onload="bodyOnLoad()">_x000D_
<div id="mydiv"></div>_x000D_
_x000D_
<!-- this script must te at the bottom of <body> -->_x000D_
<script>_x000D_
// solution G_x000D_
print(`[timestamp: ${Date.now()}] G: <body> bottom script`);_x000D_
</script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_