Window.onload vs document.onload
window.onload
is invoked when the entire page, including all dependent resources like images and stylesheets, are fully loaded. This is the green light for functions that require the whole page to be loaded and ready.
DOMContentLoaded
event fires up when the HTML is fully parsed, without waiting for stylesheets, images, and subframes to finish loading. Choose this for initializing scripts that only need the DOM structure ready.
Use DOMContentLoaded
for speedy DOM-ready actions, and window.onload
if your script needs all the external resources.
Use case comparison
The speedy choice: DOMContentLoaded
Prefer DOMContentLoaded
when your JavaScript needs the DOM ready, but not necessarily the images and style sheets. This allows your scripts to run faster, as the browser doesn't have to wait for assets to load.
Everything matters: window.onload
If your script relies on styled elements, images, or needs all frames to be fully loaded, window.onload
is the obvious choice. This ensures all required resources are loaded for your script to execute flawlessly.
Understanding the details
Code Overwriting dilemma: window.addEventListener
Directly using window.onload
can overwrite previously set onload
events. Ensure a clean code structure by attaching events with addEventListener
.
This allows adding multiple events without the fear of overwriting.
Time is of the essence: Timing issues
The DOMContentLoaded
event mitigates timing issues from dynamically loaded scripts when used correctly with addEventListener
. Performant and quick DOM-dependent concerns are well catered to.
Bye Bye jQuery
While $(document).ready()
from jQuery seems handy, consider the performance gains and code visibility improvements from using plain JavaScript. A simple DOMContentLoaded
with addEventListener()
eliminates jQuery dependencies:
Cross Browser Woes
Different browser behaviors for these events can lead to inconsistencies. Occasional console.log
can help debugging and ensure your scripts are functional across all browsers. Remember, with great powers, comes great cross-browser compatibility responsibilities.
Was this article helpful?