What is the difference between $(Document). ready() and window.onload?

Asked

Viewed 126,902 times

54

There is a difference between $(document).ready() e window.onload apart from one being Javascript and the other being jQuery?

I see both events are triggered as soon as the GIFT (Document Object Template) is loaded.

In practice as they are written:

$(document).ready(function() {

});


window.onload = function() {

};
  • take a look here: http://stackoverflow.com/questions/8396407/jquery-what-are-differences-between-document-ready-andwindow-load

  • 2

    @Jefersonleonardo doesn’t want to try an answer?

2 answers

72


The event ready is fired after the HTML document has been loaded.

The onload is only fired when whole the content is loaded (including images, videos, etc).

Note that the ready is jQuery specific. That is, it does not exist "natively". His intention is to execute something as quickly as possible after loading the document, without having to wait for all the content to be loaded.

Example of document.ready using a heavy image

$(document).ready(function(){
  console.log('Ready disparado');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div>Meu conteúdo</div>
<img src="http://joumxyzptlk.de/pics/normal/unigine/Unigine%20Valley%2010k%20(10240x5760)%20-%20000.jpg" />

Example of onload

window.onload = function(){
  console.log('Onload disparado');
}
<div>Meu conteúdo</div>

<img src="http://joumxyzptlk.de/pics/normal/unigine/Unigine%20Valley%2010k%20(10240x5760)%20-%20000.jpg" />

The event DOMContentLoaded has the same intention of ready.

Ex.:

document.addEventListener("DOMContentLoaded", function(event) {
  console.log("DOM completamente carregado e analisado");
});

for(var i=0; i< 1000000000; i++)
{}
<div>Meu conteúdo</div>

14

The event ready occurs after the HTML document has been loaded, while the event onload occurs later, when all content (e.g., images) has also been loaded.

The event onload is a standard DOM event, while the ready is specific to jQuery. The purpose of the event ready is that it should occur as soon as possible after the document is loaded, so that the code that adds the functionality for the elements on the page need not wait for all content to load.

Source

Browser other questions tagged

You are not signed in. Login or sign up in order to post.