Before delving into this, let's avoid downvoting as this is not another typical question about window.onload
vs document.onload
.
window.onload
triggers once all DOM nodes are fully loaded, while document.onload
triggers when all DOM nodes are ready without waiting for assets to fully load.
If we use window.onload
in the following example:
<!DOCTYPE html>
<html>
<head>
<title>Testing out document.onload and window.onload</title>
<script>
window.onload = function() {
alert('Loaded!');
};
</script>
</head>
<body>
<img src="https://goo.gl/0Oomrw" alt="Heavy image!" />
</body>
</html>
The script will wait for the image to be fully loaded before triggering the alert.
On the other hand, if we use document.onload
:
<!DOCTYPE html>
<html>
<head>
<title>Testing out document.onload and window.onload</title>
<script>
document.onload = function() {
alert('Loaded!');
};
</script>
</head>
<body>
<img src="https://goo.gl/0Oomrw" alt="Heavy image!" />
</body>
</html>
In this case, nothing will happen unless we make our function self-executing like so:
<!DOCTYPE html>
<html>
<head>
<title>Testing out document.onload and window.onload</title>
<script>
document.onload = function() {
alert('Loaded!');
}();
</script>
</head>
<body>
<img src="https://goo.gl/0Oomrw" alt="Heavy image!" />
</body>
</html>
Now, the script will work but won't wait for the image to fully load like it does with window.onload
.
I have a couple of questions:
Why do we need to create self-executing functions with
document.onload
, whilewindow.onload
works without making our function self-executing? It behaves the same in the latest versions of Chrome and Firefox, so I assume that's how it's intended to work, but why?What exactly is happening when we assign a function to
document.onload
? It seems to be a way to await the loading of the DOM. But when we saywindow.onload = function() { }
, are we essentially turning a window into a function? Or does the window have an event listener attached to it that is triggered by the onload event? It appears that the answer might lie within the question itself... :) Is this true?
Thank you!