What is the purpose of the "ready ()" function?

4

In scripts written in jQuery I always come across a function that is the ready() function, as the first function to be executed, see an example illustration of it:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scripttype="application/javascript">
        $(document).ready(function () {
            $("#btnexemplo").click(function () {
                alert("meow");
            });
        });
</script>
<button id="btnexemplo">Click aqui!</button>

The function ready() seems to belong to $(document) , I do not know if it is an object, and if I remove it the click event does not fire.

So, I'd like to know what the purpose of the ready() function is and how important is it to scripts written using the jQuery library?

    
asked by anonymous 28.12.2016 / 18:47

1 answer

8

The .ready() , as the Jquery documentation says:

  

[...] provides a way to execute JavaScript code once the Document Object Model (DOM) of the page is ready to be manipulated.

That is, it is an event.

It works as an approximation of the "DOMContentLoaded" event

document.addEventListener("DOMContentLoaded", callback);

When the DOM (page tree of elements) is fully loaded and ready to receive styles, events, and modifications at pipeline The callback will be called.

The basic difference between the two is that the .ready() , if called after the page is already loaded, it will still 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>

WhatdoesnothappenwithDOMContentLoaded:

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, the insertion of dynamic third-party codes, APIs and etc, which can be called with the guarantee that the page is already loaded, and not necessarily in your first call.

When you run a .click() , for example, without being inside the callback, depending on where the code is , the bind element might still not be ready to receive events because the DOM may still be in the loading phase.

Basically, it's a way to ensure that element manipulation runs successfully.

    
28.12.2016 / 18:58