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.

3
  • It is synonymous with $(document).ready(function(){}). It is called when the page is loaded so you have access to the DOM. Commented Feb 10, 2015 at 12:40
  • possible duplicate of Is $(document).ready necessary? Commented Feb 10, 2015 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. Commented Feb 10, 2015 at 12:46

4 Answers 4

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); 
Sign up to request clarification or add additional context in comments.

4 Comments

Also, OP, this notation wraps everything in an an Immediately-Invoked Function Expression ( aka IIFE ).
@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.
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.
@Jai - jep, I thought I'll provide some Google terms for the man.
2

read this you will get idea about it...

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

Comments

0

It is very similar to :

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

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.