Why does the below code (JS Bin) fire in the order 1, 5, 3, 4? And why does 2 not fire at all?
According to the answer to this question, "4" should fire before "5". That's not what is shown by the order of the alerts. However, if I change the body and img onload handlers to execute document.write
instead of alert
, then 5 will be displayed, which is consistent with that answer.
<!DOCTYPE html>
<html>
<head>
<script>
document.addEventListener("DOMContentLoaded", function() {
alert("1");
});
document.addEventListener("load", function() {
alert("2");
});
window.addEventListener("load", function() {
alert("3");
});
</script>
</head>
<body onload="alert('4')">
<h1>Hello World!</h1>
<img onload="alert('5')" src="https://developer.cdn.mozilla.net/media/redesign/img/logo_sprite.svg?2014-01" alt="Smiley face" width="42" height="42" />
</body>
</html>