Decreasing Variables in JavaScript

I am building a JavaScript compressor and I am in the "shrinking local variables" stage. I was comparing the results of my compressor to various online compressors and noticed something interesting with Dean Edwards / packer / .

Let's take this jQuery library snippet as an example:

(function( window, undefined ) {
  var document = window.document,
      navigator = window.navigator,
      location = window.location;


My compressor is returning the following code:

(function(a,b){var c=a.document,d=a.navigator,e=a.location});


but / packer / returns this:

(function(a,b){var c=a.document,navigator=a.navigator,location=a.location});


Is there a reason why / packer / doesn't compress variables after the first var in the list? Is this just a bug or is there a reason?

At first glance, it seems like my compressor is doing everything right and will give the best end result, but let's look at another example from the jQuery library:

var jQuery = (function() {

  var jQuery = function( selector, context ) {
      return new jQuery.fn.init( selector, context, rootjQuery );
    // some other vars
    // etc...


This snippet is important because the variable rootjQuery

is mentioned before it is defined.

In this case / packer / does the same and only compresses the first var in the list:

var jQuery=(function(){var c=function(a,b){return new c.fn.init(a,b,rootjQuery)},rootjQuery});


However, my compressor spares the code a bit, because although it doesn't compress rootjQuery

when it is mentioned in the return statement (since it is not yet defined), it does compress it when it is defined later.

var jQuery=(function(){var a=function(b,c){return new a.fn.init(b,c,rootjQuery)},b});


This obviously throws an error when trying to execute the code.

Is there a way to get around this? It looks like Dean Edwards noticed this problem, so he got around it by only compressing the first var in the list, so that in the random case when such a case appears, it won't throw an error.

I tried to highlight the variables that are used before they are defined, rather than compress them, but this is not so easy because in this case it is rootjQuery

used in a different scope than defined in. I have no way of knowing what scope it will be defined in until I get it.


source to share

1 answer

Now I have fixed my compressor.

As Paul Grim said in the comments, it was necessary to create a whole list of all variables and their scopes before compressing anything.

JavaScript allows things to be referenced before they are defined, so there is no way around this.



All Articles