PASSWORD RESET

Your destination for complete Tech news

What is the difference between window.onload vs $(document).ready() in javascript?

299 0
< 1 min read

window.onload is an event that occurs when the entire page (HTML, CSS, images, etc.) has finished loading in the browser. It is a good place to put initialization code that needs to run when the page loads, such as setting up event listeners or modifying the DOM.

$(document).ready() is a jQuery method that runs when the DOM is fully loaded and ready to be manipulated. It is equivalent to the window.onload event, but it is more efficient to use because it runs as soon as the DOM is ready, rather than waiting for all of the page resources to finish loading.

Here is an example of how you might use window.onload:

window.onload = function() {
  console.log("Page has finished loading!");
  // Initialize event listeners or modify the DOM here
};

And here is an example of how you might use $(document).ready():

$(document).ready(function() {
  console.log("DOM is ready!");
  // Initialize event listeners or modify the DOM here
});

Note that you can only use $(document).ready() if you have included the jQuery library in your project. If you are not using jQuery, you will need to use window.onload or another method to run your initialization code when the DOM is ready.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.