Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What is the difference between window.onload and document.onload in Javascript?
In JavaScript, window.onload and document.onload handle different loading stages of a web page. Understanding their timing differences is crucial for proper DOM manipulation and event handling.
document.onload
The document.onload event fires when the HTML document has been completely loaded and parsed, but before images, stylesheets, and other external resources finish loading. However, document.onload is not widely supported across browsers. Instead, use DOMContentLoaded event for similar functionality.
window.onload
The window.onload event fires when the complete page has loaded, including all images, scripts, CSS files, and other external content. This ensures all resources are available before your code executes.
Timing Comparison
| Event | Trigger Time | Includes Images/CSS? | Browser Support |
|---|---|---|---|
DOMContentLoaded |
DOM fully loaded | No | Excellent |
window.onload |
All resources loaded | Yes | Universal |
Example: window.onload for Image Animation
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Animation</title>
<script>
var imgObj = null;
function init() {
imgObj = document.getElementById('myImage');
imgObj.style.position = 'relative';
imgObj.style.left = '0px';
console.log('Image ready for animation');
}
function moveRight() {
if (imgObj) {
imgObj.style.left = parseInt(imgObj.style.left) + 10 + 'px';
}
}
window.onload = init;
</script>
</head>
<body>
<img id="myImage" src="/images/html.gif" alt="HTML logo" />
<p>Click button below to move the image to right</p>
<button onclick="moveRight()">Move Right</button>
</body>
</html>
Modern Alternative: DOMContentLoaded
<script>
document.addEventListener('DOMContentLoaded', function() {
console.log('DOM fully loaded - faster than window.onload');
// DOM manipulation code here
});
window.addEventListener('load', function() {
console.log('All resources loaded including images');
// Code requiring all resources
});
</script>
When to Use Which
Use DOMContentLoaded when you need to manipulate DOM elements but don't need images or stylesheets to be fully loaded.
Use window.onload when your code depends on images, CSS, or other external resources being completely loaded.
Conclusion
window.onload waits for all resources while DOMContentLoaded fires earlier when just the DOM is ready. Choose based on whether you need external resources loaded first.
