javascript compression tip
by Kae Verens on Jul.21, 2010, under javascript, programming, web development
I was just reading through the latest article in A List Apart, and there was a little bit of discussion on the following snippet of code:
function getValueFor(data){
var value;
if (firstCondition(data)){
value = 1;
} else if (secondCondition(data)){
value = 2;
} else if (thirdCondition(data)){
value = 3;
} else {
value = 4;
}
return value;
}
When compressed with YUI Compressor, that’s reduced to 140 bytes.
By changing it slightly, you can reduce it further:
function getValueFor(data){
var value = 4;
if (firstCondition(data)){
value = 1;
} else if (secondCondition(data)){
value = 2;
} else if (thirdCondition(data)){
value = 3;
}
return value;
}
That’s reduced it to 133 bytes.
I think Nicholas missed a trick, though – by removing all the “else if”s and replacing them with ternary operators, he could reduce it even further:
function getValueFor(data){
return firstCondition(data)
?1
:secondCondition(data)
?2
:thirdCondition(data)
?3
:4;
}
The above will reduce to 95 bytes. That’s 95, where the previous record was 133.
July 21st, 2010 on 10:53 am
Try to delete as much \n as possible and put everything in the same line, and you will possibly reduce again
July 21st, 2010 on 11:53 am
YUI Compressor does that automatically, so you can write properly formatted code and not worry too much about how large it is.
July 21st, 2010 on 6:50 pm
I wonder how this fares out with the Google Closure compressor.
July 21st, 2010 on 7:06 pm
Yeah, Closure can get it to 87 bytes gzipped. Check it out here: http://closure-compiler.appspot.com/home
July 21st, 2010 on 8:39 pm
heh – I wasn’t counting gzipping, which happens automatically when the server sends it. Pre-gzip, the Closure thing does 95 bytes – the same as YUI Compressor.
Must try a few of my larger scripts in them…
July 21st, 2010 on 11:49 pm
Yea, do! It’s really very good!
July 22nd, 2010 on 4:30 am
I love this kind of games anyway.
Well done!
^_^