1

In some tutorials, I find the jQuery declaration like this:

(function($){
    //Init some code

})(jQuery);

how this works in jQuery?

I usually init the jQuery main.js like this:

$(document).ready(function(){
 //Init some code
});
Antonio Morales
  • 856
  • 2
  • 11
  • 30

1 Answers1

4

Both codes are very different.

$(document).ready(function(){
  //Init some code
});

This will be executed whenever the document finishes loading. It can be placed everywhere. Read more here. While:

(function($){
//Init some code

})(jQuery);

is self-executing function. It will be executed when browser comes to it. If you place this in the begining of your code it will execute immentaly, so if your elements are after this self-executing function, the jquery selectors might not work, since at that time the elements won't exists at all. Basically this code is a function which will be executed at the same time as declarated, so the jQuery will be passed as first parameter ($).

Tl;dr; Position of document.ready doesn't matter - it will be executed on document load done, while the position of the self-executing function should be only after the dom element declaration.

Community
  • 1
  • 1
Deepsy
  • 3,528
  • 5
  • 32
  • 66