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

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

  •  12-07-2023
  •  | 
  •  

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.

有帮助吗?

解决方案

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top