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:

Featurewindow.onload$(document).ready()
Execution TimeAfter all page resources loadAs soon as the DOM is ready
DelayAffected by slow-loading assetsNot affected by external resources
Use CaseEnsuring all assets are loadedQuick DOM manipulation
jQuery Required?NoYes

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.

Leave a comment

Your email address will not be published. Required fields are marked *