Reputation: 23892
window.onload
from my reading sounds like it is loosely interchangeable with document.onload
but my experience has shown this is incorrect. I've inherited a JS script and I'm not sure how to correct it. I want the JS to execute once the DOM has loaded, not once all resources have been loaded. How can I do this?
Currently I have:
window.onload = initDropMenu;
I've tried:
document.onload = initDropMenu;
which just results in the menu not loading. I've also tried removing the line altogether from the JS and just having the DOM execute it via:
<body onload="initDropMenu()">
that also resulted in no menu, and in no errors in the console. My JS knowledge is limited, what am I missing here?
Upvotes: 5
Views: 4676
Reputation: 17546
Load Event on window:
The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images, scripts, links and sub-frames have finished loading.
[source: developer.mozilla.org]
<script>
window.onload = function(){ init(); };
</script>
Load Event on HTML Elements:
The
load
event is fired when a resource and its dependent resources have finished loading.
[source: developer.mozilla.org]
<!-- When the image is loaded completely -->
<img onload="image_loaded()" src="w3javascript.gif">
<!-- When the frame is loaded completely (including all resources) -->
<iframe onload="frame_loaded()" src="about.html">
<!-- When body loaded completely (including all resources, images and iframes) -->
<body onload="init()">
Many forums even some answers in this site may mislead you, but the load
event on body element is not only just equivalent to load
event on window, it is the exact same event. The following quote clarifies it.
For historical reasons, some attributes/properties on the
<body>
and<frameset>
elements actually set event handlers on their parent Window object. (The HTML specification names these: onblur, onerror, onfocus, onload, onscroll.)
[source: developer.mozilla.org]
The DOMContentLoaded Event:
What developers should use is DOMContentLoaded
event on document. It fires when the html has loaded and parsed completely.
document.addEventListener("DOMContentLoaded", function(event) {
alert("Document is ready");
});
The DOMContentLoaded event is fired when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading. A very different event load should be used only to detect a fully-loaded page. It is an incredibly popular mistake to use load where DOMContentLoaded would be much more appropriate, so be cautious.
[source: developer.mozilla.org]
Perhaps this is the only answer regarding this topic that has proper References
Upvotes: 12