Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery .ready() vs window.onload [duplicate]

Tags:

Are there any advantages of using the Jquery ready() function over window.onload?

// Jquery ready $(document).ready(function() {  });  // window.onload window.onload = function () {  } 
like image 320
James Avatar asked Feb 13 '14 00:02

James


People also ask

What is the difference between document ready () and window onload ()?

The major difference between the JavaScript's onload and jQuery's $(document). ready(function) method is that: The onload executes a block of code after the page is completely loaded while $(document). ready(function) executes a block of code once the DOM is ready.

Can I have multiple jQuery document ready () method in a HTML page?

Yes we can do it as like I did in below example both the $(document). ready will get called, first come first served.

What is document ready and window load in jQuery?

The Difference between $(document). ready() and $(window). load() functions is that the code included inside $(window). load() will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the document ready event fires before all images,iframes etc.

What is the benefit of using document ready in jQuery?

jQuery document ready is used to initialize jQuery/JavaScript code after the DOM is ready, and is used most times when working with jQuery. The Javascript/jQuery code inside the $(document). ready() function will load after the DOM is loaded, yet before the page contents load.


1 Answers

Depends on what you want to do.

  • jQuery ready will run your code when the HTML is all ready, but before images and other resources have finished. This is the earliest possible time that you can change the DOM with JavaScript, so it's widely used. (In modern browsers it's replaced by the native event DOMContentLoaded).
  • window.onload (the load event) runs after everything has finished loading. Images, Flash, and some scripts, but usually not stylesheets. Use this for code that should run only when the page won't change any more.

Also, with window.onload you can only attach one listener, but you can attach as many as you want with jQuery ready. To attach more than one event on window.onload, use addEventListener:

window.addEventListener('load', function () {  }, false); 
like image 76
rvighne Avatar answered Oct 12 '22 15:10

rvighne