jQuery best practices in case of $('document').ready

前端 未结 9 1130
孤街浪徒
孤街浪徒 2020-12-07 11:35

I was researching on jQuery best practices and found this article by Greg Franko

Normally, I do:

$(\"document\").ready(function() {
    // The DOM i         


        
9条回答
  •  囚心锁ツ
    2020-12-07 12:13

    If you use $ as an alias for jQuery then

       $(document).ready(function(){})
    

    is same as

      (function($, window, document) {
    
      // The $ is now locally scoped 
    
     // Listen for the jQuery ready event on the document
      $(function() {
    
        // The DOM is ready!
    
      });
    
      // The rest of the code goes here!
    
     }(window.jQuery, window, document));
    

    As pointed out in an earlier answer, the second method insulates you from using $ alias freely for jQuery as it passes the jQuery object to the Immediately invoked function expression, which basically keeps the variables and code within it private, and does not pollute the global namespace.

    In short, if you resort to the first method and use other libraries using $, you will end with conflict.

提交回复
热议问题