Question

I just discovered that YUICompressor (2.4.7) does not combine var declarations. For example,

var x = 1;
var y = 2;

compresses to

var a=1;var b=2;

I assume it would be reasonable to expect a minifier to be able to combine consecutive var declarations, like so:

var a=1,b=2;

But my real question is is it reasonable to expect/possible (for a minifier) to automatically and safely combine non-consecutive var declarations in a single function?

Était-ce utile?

La solution

It depends. If you're talking about declarations with initialization then: No.

Consider this:

(function () {
    var x = 1;
    console.log(y); // undefined
    var y = 2;
})();

(function () {
    var x = 1, y = 2;
    console.log(y); // 2
})();

However, the following is safe and should be done by minifiers:

(function () {
    var x = 1, y;
    console.log(y); // undefined
    y = 2;
})();

It is certainly possible; the compressor scans the whole function for contained var statements prior to generating output. This is necessary to compress variable names.

Note that there is one possible tricky variant, which consists in extending the parameter list, and thus saving extra bytes by completely eliminating any var statements:

(function (x,y) {
    x = 1;
    console.log(y); // undefined
    y = 2;
})();

However, this changes the function's (rarely used) length property and thus is not to be expected from minifiers.

Autres conseils

I know of one example where this would not be desirable. See this question Have I reached the limits of the size of objects JavaScript in my browser can handle?

That question was about a bug when the initialization of a variable happened in a single var statement. The question was about assigning a really gigantic literal to a variable which failed. The solution in the end was to split the object into separate var declarations.

Therefore, if compressors always did that, that would cause your code to be more likely to run into that kind of problem

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top