difference between window.load(); and $(document).ready(function(){ }); ?
When working with JavaScript and jQuery, it’s essential to understand the difference between window.onload
and $(document).ready()
. Both are event handlers that execute code after the page loads, but they trigger at different times.
What is window.onload
?
The window.onload
event fires only after the entire webpage, including images, stylesheets, and scripts, has fully loaded. This ensures that all elements are available before executing JavaScript. However, if large images or slow resources exist, execution can be delayed.
Example:
window.onload = function() {
console.log("Page fully loaded with all resources.");
};
What is $(document).ready()
?
The $(document).ready()
function executes as soon as the HTML document is fully loaded, without waiting for external assets like images or stylesheets. This makes it ideal for manipulating the DOM as early as possible.
Example:
$(document).ready(function() {
console.log("DOM is ready, but images and other resources may still be loading.");
});
Key Differences:
Feature | window.onload | $(document).ready() |
---|---|---|
Execution Time | After all page resources load | As soon as the DOM is ready |
Delay | Affected by slow-loading assets | Not affected by external resources |
Use Case | Ensuring all assets are loaded | Quick DOM manipulation |
jQuery Required? | No | Yes |
When to Use Which?
- Use
window.onload
when you need to work with elements that depend on external resources, such as checking image dimensions. - Use
$(document).ready()
when you need to manipulate the DOM as soon as possible, without waiting for external assets.