IIFE inside $ (document). Already or vice versa

My colleague made extensive use of IIFE inside (document). already in its code. Now I read this post:

JQuery best practice using $ (document) .ready inside IIFE?

This made me wonder if we should use $ (document) .ready inside IIFE, or is it just fine, just like my colleague.

Basically, its code is configured as follows:

jQuery(function() {
    (function($) {
        //...
        // Code here
        //...
    })(jQuery);
});

What does he do normally?

+4
source share
2 answers

Some may argue that this is a matter of style / opinion, but if you consider the typical goal of IIFE in this context, I believe that the answer is yes, it is acceptable to use an alternative method, but there is a potential drawback .

Wikipedia , :

, , .

, . . , , ready , , , IIFE .


, : JavaScript, DOM, IIFE, IIFE. , - :

// Non-DOM-ready-required code here (NOT scope-safe)
jQuery(function() {
    (function($) {
        //...
        // DOM-ready-required code here
        //...
    })(jQuery);
});

IIFE:

(function($) {
    // Non-DOM-ready-required code here (scope-safe)
    $(function() {
      //...
      // DOM-ready-required code here
      //...
    });
 })(jQuery);
+5

-, . $(document).ready, .

/*jQuery(*/function() {
    (function($) {
        //...
        // Code here
        //...
    })(jQuery);
}/*);*/

IIFE jQuery . ,

/*jQuery(*/function() {

        //...
        // Code here
        //...

});

, IIFE, - jQuery $.

, , - IIFE. ,

jQuery(function() {
    // IIFE
    (function($) {
        //...
        // Code here
        //...
    })(jQuery);
    // IIFE 2
    (function($) {
        //...
        // Code here
        //...
    })(jQuery);
});

IIFE .

:

, $(document).ready IIFE -, .

, , , , . , , , .

(function($) {     
 $(document).ready(function() {   
    // other code here  
  });    
})(jQuery);

//(function($) {     
 $(document).ready(function() {   
    // other code here  
  });    
//})(jQuery); 

. , IIFE , jQuery $.

:

(function($) {    
   // other code here 1
 $(document).ready(function() {   
    // other code here 2 
  });    
})(jQuery);

IIFE , , other code here 1, . $(document).ready().

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

jQuery(document).ready(function() {   
   // other code here 2 
}); 

.

, IIFE , , , , , ( ).

+1

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


All Articles