Given that when minified JavaScript variables will be simplified what is the best way to declare or use the variable for window, document, undefined, etc.?

1st way

(function ($, win, doc, undefined) {
}(jQuery, window, document));

2nd way

(function () {
    var $ = jQuery,
        win = window,
        doc = document,
        undefined;
}());
有帮助吗?

解决方案

For minified code, shorter (less bytes to be transferred) is always better. So, for a minified file the first option would be best:

(function($,w,d,u){})(jQuery,window,document); 46 characters.

Compared to the other option:

(function(){var $=jQuery,w=window,d=document,u=undefined;})(); 62 characters.

P.S. You did your closures wrong. (function(){}()) will throw a syntax error. (function(){})() won't.

其他提示

It doesn't matter, write your code keeping a legible and maintainable format, and for production then use a minifier that will shrink your code to something really small.

You can even automatize the whole process by using something like make

Keep in mind that premature optimization is the root of all evil (you're trying to minimize the size of your code beforehand)

I don't believe it really makes a difference, except that the second way takes up more space. I personally prefer the second way, as I think it is more readable.

But for minifying, you DEFINITELY want to go with the first way. Much less space used.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top