The .ready()
, as the Jquery documentation says:
[...] offers a way to execute Javascript code as soon as the Document Object Model (DOM) of the page is ready to be manipulated.
I mean, it’s an event.
Acts as an approach to the event "Domcontentloaded"
document.addEventListener("DOMContentLoaded", callback);
When the DOM (page element tree) is fully loaded and ready to receive styles, events and modifications to pipeline the callback will be called.
The basic difference between the two is that the .ready()
, if it is called after the page is already loaded, it will still run callback. For example:
$(document).ready(function(){
/* Página já carregada */
$('div').css({
width: '100px',
height: '100px',
background: '#333'
});
setTimeout(function(){
/* A página já carregou, mas o evento ainda é constantemente executado */
$(document).ready(function(){
$('div').css({
background: 'red'
})
})
}, 2000)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
What does not happen with the DOMContentLoaded
:
document.addEventListener('DOMContentLoaded', function(){
var div = document.querySelector('div');
div.style.width = "100px";
div.style.height = "100px";
div.style.background = "#333";
setTimeout(function(){
/* O evento não vai ser chamado dessa vez, pois isso só acontece no carregamento inicial da página. */
document.addEventListener('DOMContentLoaded', function(){
div.style.background = "#fff";
})
})
})
<div></div>
The main advantage of .ready()
, in my view, in this regard, the insertion of dynamic third-party codes, Apis and so on, which can be called with the guarantee that the page is already loaded, and not necessarily on your first call.
When you run a .click()
, for example, without being inside the callback, depending on where the code is, the item to be received bind, may not yet be ready to receive events, as the DOM may still be in the loading phase.
Basically, it is a way to ensure that the manipulation of elements is executed successfully.