Mark Brown Mark Brown - 4 months ago 32
jQuery Question

$(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.

Answer

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.

Comments