$(document).ready shorthand
Is the following shorthand for $(document).ready
?
(function($){
//some code
})(jQuery);
I see this pattern used a lot, but I'm unable to find any reference to it. If it is shorthand for $(document).ready()
, is there any particular reason it might not work? In my tests it seems to always fire before the ready event.
The shorthand is:
$(function() {
// Code here
});
The shorthand for $(document).ready(handler)
is $(handler)
(where handler
is a function). See here.
The code in your question has nothing to do with .ready()
. Rather, it is an immediately-invoked function expression (IIFE) with the jQuery object as its argument. Its purpose is to restrict the scope of at least the $
variable to its own block so it doesn't cause conflicts. You typically see the pattern used by jQuery plugins to ensure that $ == jQuery
.
The correct shorthand is this:
$(function() {
// this behaves as if within document.ready
});
The code you posted…
(function($){
//some code
})(jQuery);
…creates an anonymous function and executes it immediately with jQuery
being passed in as the arg $
. All it effectively does is take the code inside the function and execute it like normal, since $
is already an alias for jQuery
. :D