What's the difference between $ (document) .ready () and window.onload?

28

Is there a difference between $(document).ready() e window.onload plus one being JavaScript and the other being jQuery?

I see that both events are triggered as soon as DOM Document Objects) is loaded.

In practice as written:

$(document).ready(function() {

});


window.onload = function() {

};
    
asked by anonymous 08.02.2017 / 13:17

2 answers

39

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

onload is only triggered when all content is loaded (including images, videos, etc.).

Notice that ready is specific to jQuery. That is, it does not exist "natively". It is intended to run as fast 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>Meuconteúdo</div><imgsrc="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 DOMContentLoaded event has the same intent as 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>
    
08.02.2017 / 13:28
10

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

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

Font

    
08.02.2017 / 13:28