How should I initialize jQuery?

The second example you show is a self executing anonymous function. Every separate JS file you use would probably benefit from using it. It provides a private scope where everything you declare with the var keyword remains inside that scope only:

(function($){
   var special = "nice!";
})(jQuery);

alert(special); // would be undefined

The first example is shorthand for $(document).ready which fires when the DOM can be manipulated.

A couple cool things about it. First, you can use it inside the self executing function:

(function($){
   $(function(){
      // Run on DOM ready
   });

   // Run right away
})(jQuery);

Secondly, if all you need is a few lines in document ready, you can combine both the private scope and the DOM ready function like this:

jQuery(function($){
   // $ = jQuery regardless of what it means
   // outside this DOM ready function
});

Leave a Comment