Packer friendlier JavaScript
recently handgestrickt wrote about JSmin, a JavaScript minifier. this minifier takes care of the problem of automatic semicolon insertion. after a little investigation on the internet we found the article "Packer friendly JavaScript" by Andrea Giammarchi, who explains in detail, how to make JavaScript code more clean, so it can be packed more efficient. after a little bit of testing with JSmin, we found ways to make code really be on one line. examples:
//normal code, always semicolon
var a=0;
//one liners must end with semicolon
if(foo == bar) while(foo) a += bar;
//switch, for, while always with semicolon
switch(foo) {
case bar: a=0; break;
};
for(var a=0;a<foo;a++) {
bar += a;
if(bar > 100) bar = 100;
};
for(var foo in bar) {
bar.search(/\s/,'_');
window.alert(bar);
};
while(foo) {
a += bar;
bar = foo;
};
//several examples of if, else if and else constructs
if(foo == 0) {
foo = 1;
};
if(foo == 0) {
foo = 1;
} else { //this syntax here is necessary, otherwise we have a line break after minifying
foo += bar;
};
if(foo == 0) foo = 1;
else if(foo < -100) foo = -100;
else foo += bar;
if(foo == 0) {
foo = 1;
} else if(foo < -100) foo = -100;
else foo += bar;
if(foo == 0) foo = 1;
else if(foo < -100) {
foo = -100;
} else foo += bar;
if(foo == 0) foo = 1;
else if(foo < -100) foo = -100;
else {
foo += bar;
};
//long expressions should be either one line or split into several expressions
var text = 'imagine a very long text here that is not split into several lines by +.';
var text = 'imagine a very lone text ';
text += 'that is not split into several ';
text += 'lines by +';
//more advanced things like functions, arrays, hashes, objects
function foo(bar) {
return 100;
};
var foo = [
[1,0],
[1,1]
];
var foo = {
key1: value1,
key2: value2
};
var foo = {
key1: value1,
key2: value2,
key3: [
[1,0],
[1,1]
],
key4: {
key1: value1,
key2: value2
},
key5: function foo(bar) {
return 100;
}
};
//finally try...catch
try {
if(document.throws_object_does_not_support_property_or_method) foo = true;
} catch(e) {
foo = false;
};
related:
earlier post on 07. April 2007
JSmin
"Packer friendly JavaScript"

