[RESOLVED]what's the difference between for $(function() {…}) and (function($) {…})(jQuery);

I noticed that many other people wrapped there jquery code between

$(function() {
   //my code here
})

or

(function($) {
   //my code here
})(jQuery)

what’s the difference between these two wrappers?

I think one of the benefit of latter is if your code change the shortcut $ to other than jQuery, you can still get it running. Are there more difference?

You might be interested in
this rather in-depth discussion of the differences
between the two.

First Example

$(function() {
   // Code
})

Your first example functions simply as an alias for the
jQuery Ready event
 and indicates that it will trigger the DOMReady event to let the DOM know that your appropriate jQuery resources have loaded and can be accessed. You might also commonly see this same code written as follows :

$(document).ready(function() {
   // Code
})

Second Example

(function($) {
   // Code
})(jQuery)

Your second example uses the
Javascript Module pattern
 to provide "modularity", privacy and encapsulation for your code.

The implementation of this is a function that is immediately invoked by the calling (jQuery) parenthesis. The purpose of passing jQuery in to the parenthesis is to provide local scoping to the global variable. This helps reduce the amount of overhead of
looking up the $ variable, and allows better compression / optimization for minifiers in some cases.

Leave a Reply