What is the difference in code execution when wrapping these methods

(function($) { // ... code here ... })(jQuery); jQuery(function($) { /// ... code here ... }); 
+4
source share
4 answers

The first call is immediate, the second when the DOM is loaded and ready.

+10
source

In the first case, jQuery is passed directly and reassigned to use the local variable $ in the method. In the first case, $ will act like jQuery, as you are used to. This is often used for plugins that do not assume that $ represents jQuery (since jQuery may refuse to not use $ if there is a conflict).

In the second case, jQuery only does this conflict protection for you, providing you with a local view of $ that will not conflict with any other libraries.

The first is also called when it is analyzed, as mentioned by others. The leading parenthesis is a convention, implying that the function definition itself is followed by a set of open / clos parentheses, which runs immediately. The second is caused by page loading.

+3
source

The first is used to steal the $ character when working with multiple frames, and is also used to create local variable declarations (which the last example also does). The last example is used to execute scripts when the page loads, but can be more clearly written as:

 $(function() { /// code }); 
+1
source

Check with jquery with other documents .

jQuery (function ($) {});

If you include jQuery in front of another library, you can use "jQuery" when you are doing some work with jQuery, and "$" is also a shortcut to another library. There is no need to override the $ function by calling "jQuery.noConflict ()".

 <html> <head> <script src="jquery.js"></script> <script src="prototype.js"></script> <script> // Use jQuery via jQuery(...) jQuery(document).ready(function(){ jQuery("div").hide(); }); 

(function ($) {}) (jQuery);

Use the following technique, which allows you to use $ inside a code block without constantly rewriting $:

(function ($) {/ * some code that uses $ * /}) (jQuery)

+1
source

Source: https://habr.com/ru/post/1344392/


All Articles