Reputation: 3088
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 ?
Upvotes: 3
Views: 168
Reputation: 105029
The first one is a jQuery DOM Ready function definition, while the second one is a function closure that 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.
Upvotes: 8
Reputation: 1074238
The first one is a shortcut for jQuery.ready
. It calls the function you give it only when the DOM is fully ready to be manipulated (which it typically isn't when this script first runs; hence the callback) — e.g., when you can safely look for elements by their ID, or by CSS selector, add new elements, etc., etc.
The second runs the function immediately (potentially before the DOM is ready to be manipulated) and passes the jQuery
object in as a parameter named $
. Within the function, you can safely assume that $
references the jQuery object, whereas without this you can't if you're using jQuery.noConflict
to release the $
back to whatever used to have it (perhaps Prototype) before jQuery was loaded. This technique is useful when you have a lot of code written with $
, but then find you have to co-exist with Prototype or something else that also wants to use $
. You just put all of your code within the anonymous function.
You can do both things together if you like:
jQuery(function($) {
// Code that uses `$` and expects the DOM to be ready to be
// manipulated goes here
});
Upvotes: 3