views:

67

answers:

2

I've been looking at how some jQuery plugins work and I've seen the following acting as a closure around the whole plugin

$(function(){
    // plugin code here

});

(function($){
    // plugin code here

})(jQuery);

What is the difference between these two ?

+8  A: 

The first one is a jQuery DOM Ready function definition, while the second one runs immediately when it's parsed and is executed with jQuery object as a parameter.

The first one is usually used on your pages when you want something to execute when your page loads all document elements exist (document is ready).
The second one is usually used with plugins because it creates a closure so you can define privates in it that won't be accessible to outside code.

Robert Koritnik
i know what you mean but slightly ambiguous. The first one executes when the DOM is ready (all html elements exist). The second executes immediately (as soon as its parsed). "when page loads" is a bit confusing
Andrew Bullock
Robert Koritnik
+2  A: 
T.J. Crowder