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