Search code examples
javascriptjqueryminifyuglifyjsyui-compressor

How many globals make sense to be passed to the IIFE wrapper?


To which extent does it make sense to pass plenty of global values to an IIFE?

The common thing is just to pass 3 as far as I see everywhere (window, document and undefined). But... would it make sense to pass more if they are used more than 10 times in the code just for the fact of minification?

In my case I found the global variable Math 14 times in the code. It would make sense to pass it to an IIFE in order to save 42 bytes. Which in this case is not a lot, but if we sum bit by bit different global variables, then it would always make sense to pass as many global variables as possible, right? (Symbol, Object, Error, Date, JSON...)

(function($, window, document, Math, undefined) {
    $.fn.mydemo = function() {

    };
}(jQuery, window, document, Math));

Then, why isn't this a common approach?

Update:

To explain the 42 bytes of reduction:

  • Math = 4 characteres
  • 1 character = 1 byte
  • 14 times Math = 56 bytes
  • Math will get replaced by a single character after minification
  • As the function can be defined as function($, w, d, m, u)
  • 14 characters of the shorten word Math (m) = 14 bytes
  • 56 - 14 = 42 bytes of reduction

Solution

  • would it make sense to pass more if they are used more than 10 times in the code just for the fact of minification?

    If you care that much about minification, sure, why not?

    The common thing is just to pass 3 as far as I see everywhere (window, document and undefined)

    Yes, altough you see not passing document, or passing jQuery (aliased as $), just as often. And of course it's not only about minification, but about performance, and you only care for window and document on that behalf.

    it would always make sense to pass as many global variables as possible, right?

    Well, except you don't use them in your code. Symbol, Object, Error, Date, JSON, Math and the others are not needed that often in most code. And developers don't like to do those byte counts you are suggesting every time they change a bit of code, so this IEFE boilerplate just stays as it is (and imho there's much cargo cult to it).

    You would let your minifier do this automatically if you'd really care.