Difference between wrapping jQuery blocks by starting with "jQuery(function..." vs ending with " })(jQuery);"

StackOverflow https://stackoverflow.com/questions/23375545

  •  12-07-2023
  •  | 
  •  

Question

I've just started learning jQuery and was wondering what the difference was between a chunk of jQuery code wrapped like this:

jQuery(function ($) {
    //code here
});

vs wrapping like this:

(function ($) {
    //code here
})(jQuery);

... or if there is a difference at all.

Was it helpful?

Solution

There is an important difference, the first is a DOM ready handler, it waits until the document is ready and all elements can be accessed.

The second one is just an immediately invoked function expression, it executes immediately and does not wait for the document to be ready.

Both of them creates a local scope where the value of $ equals jQuery

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top