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

前端 未结 9 1132
孤街浪徒
孤街浪徒 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:05

    The only difference between your code and the "suggested" approach is compatibility and possibly better compression. There are no speed differences.

    Passing window.jQuery as the first argument to your IIFE (immediately-invoked function expression) and naming it $ within the IIFE will just allow you to use jQuery without interfering with other libraries that assign themselves to the global $. If you don't use any other libraries that assign themselves to the global $, the first argument to your IIFE isn't going to serve any purpose.

    Passing window and document to your IIFE will allow JS minifiers to transform your code into something like this (without the whitespace), which gives you slightly better compression:

    (function(a, b, c) {
        a(c).ready(function() {
            // ...
        });
    })(window.jQuery, window, document);
    

    Unless you use window and document extensively, I would just do:

    ;(function($) {
        $(function() {
            ...
        });
    })(jQuery);
    
    0 讨论(0)
  • 2020-12-07 12:12

    You can use document ready event using jquery, event occure when document is fully loaded.

     $(function () {
        setTimeout(function () {
            // your code
        }, 0);
    })
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题