0

I've been seeing this pattern in various projects I learn from, sometimes when using jQuery developers wrap their code in this function:

jQuery(function ($) {
    'use strict';

    /* Application code */

}($)); /* End jQuery */

I was trying to look up the explanation in jQuery docs, but didn't really find much. Could you please explain to me why and when should this be used? And are there better practices / alternatives for something like this.

Ilja
  • 44,142
  • 92
  • 275
  • 498
  • It is synonymous with `$(document).ready(function(){})`. It is called when the page is loaded so you have access to the DOM. – Mr. Polywhirl Feb 10 '15 at 12:40
  • possible duplicate of [Is $(document).ready necessary?](http://stackoverflow.com/questions/4643990/is-document-ready-necessary) – Mr. Polywhirl Feb 10 '15 at 12:41
  • 1
    This doesn't look like a regular pattern, actually I looks partly _useless_. The function `function ($) {}` immediately is invoked with `$` and the result of it is passed to `jQuery()` as parameter. – t.niese Feb 10 '15 at 12:46

4 Answers4

4

The $ which is an alias for jQuery, sometimes it gets collide with other javascript libraries like mootools which also uses $ sign internally.

So you have just secured the $ jQuery alias for your code within the scope of the method:

jQuery(function ($) {
    'use strict';

    /* Application code */

}($));

another similar approach is having a scope like this:

(function($){
    $(function(){ // <----here you have just secured the $ for your code.
        'use strict';

        /* Application code */
    });
})(jQuery);
Jai
  • 74,255
  • 12
  • 74
  • 103
  • Also, OP, this notation wraps everything in an an Immediately-Invoked Function Expression ( aka IIFE ). – Jochen van Wylick Feb 10 '15 at 12:49
  • @spike true! That is what i posted in the answer but did not used the term _IIFE_ and doc ready just fires once in a page so that would do i think. – Jai Feb 10 '15 at 12:50
  • Just as an addition: As long as the `function ($) {'use strict'}($)` does not return a function then the outer `jQuery()` is useless. Even then it might be misleading. – t.niese Feb 10 '15 at 12:51
  • @Jai - jep, I thought I'll provide some Google terms for the man. – Jochen van Wylick Feb 10 '15 at 12:51
2

read this you will get idea about it...

http://api.jquery.com/jquery.noconflict/

Vikas Kad
  • 1,013
  • 1
  • 18
  • 38
0

It is very similar to :

$(document).ready(function(){});
ram
  • 2,275
  • 3
  • 27
  • 38
0

Without the outside wrapper, it is a plugin definition, see: Basic plugin creation.