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

前端 未结 9 1380
孤街浪徒
孤街浪徒 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);
    

提交回复
热议问题