What is the function of the function in jQuery and what is the correct way or time to use it?

10

Whenever I go to work with jQuery I simply create:

$(function() {

});

Because it was the first form I learned, at first I thought it was an "int main ()" pattern in C, but then I came across other shapes like:

$( document ).ready(function() {

});

$(function() {

});

$j(function() {

});

function funcao(jQuery) {

}

$( document ).ready(funcao);

What's the right way to use it? Or when is the right time to use it? Why does not pure JavaScript need? What is your role?

    
asked by anonymous 16.10.2017 / 20:45

2 answers

7

To be honest, they are very similar. When to use:

$(function() {

});

is a shorthand for:

$( document ).ready(funcao);

What more experienced programmers use. When to use:

$j(function() {

});

Actually the same as the first example, except that the alias for jQuery is in $j , perhaps because $ is being used, like this:

var $ = minhaLib(); // alias para outra biblioteca qualquer
$j = jQuery.noConflict(); // alias para o jQuery

$(document).on( "ready", manipulador) was deprecated in version 1.8 and removed in 3.0

That's because it would only execute the callback if it were attached before the document was ready. This is because jQuery has slightly altered how to handle asynchronous events, by this motive.

Some topics about:

  • link
  • link
  • 16.10.2017 / 21:01
    6
    $(function() { ... }); 
    

    It's just a shorter way to write

    $(document).ready(function() { ... });
    

    Both will run when your DOM is ready for use. Home Here's a snippet of code:

    $( document ).ready(function() {
    
    });
    

    is the same as:

    function funcao(){ ... }
    $(document).ready(funcao);
    

    The difference is that in the former the function is anonymous, and therefore there will only exist in $(document).ready , in the second, the function funcao exists globally. Both define a handler for the event of ready of document

    $j(function() {
    
    });
    

    $ j here is probably just an alias for the object jQuery , or $ , that someone created.

    Functions are the same in any language, a block of code that does something. What changes is just the syntax.

    jQuery exists to bring us some tools to make it easier to work with JavaScript. But everything that is done with jQuery can be done just with pure JavaScript.

        
    16.10.2017 / 21:00