Sunday, November 18, 2007

Notes on JavaScript Compression

Dean Edwards: Notes on JavaScript Compression

The most efficient way to serve compressed JavaScript is to first run your code through a JavaScript compressor that shrinks variable and argument names, and then serve the resulting code using gzip compression.

These JavaScript compressors are capable of shrinking variable and argument names:

Both the YUI compressor and Packer use scoping wisely so that variable names are substituted with “a”, “b” and “c” etc all the way down. This produces patterns that lead to more optimal gzip compression rates.

Packer

If you can’t use gzip compression for some reason, then Packer with base62 encoding turned on, is the next best thing. Scripts compressed with Packer are unpacked using one pass of a RegExp on most platforms. However, this still introduces an overhead for larger scripts. The “Decode” button on the Packer page will tell you how long the decode time is, typically 0 - 200 milliseconds. The next release of Packer will improve the decode time by about 10%. Compressors with more complex compression algorithms can have very high decode times.

The strictness of Packer trips some people up, especially function declarations requiring a terminating semi-colon. This is not a habit for many JavaScript programmers. In this case I recommend using Julien Lecomte’s compressor first and then running the code through Packer for base62 compression. Remember that base62 compression is only necessary if you can’t use gzip.

Update: Check out CompressorRater!