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