Compressing Javascript

I've recently found that the javascript files on the sites I build can get pretty large. Adding AJAX, AHAH, and even just simple controls to sites can quickly produce large javascript files that are well over 100K in size. To keep these files at a manageable size for end users we can compress them. Let's take a look at two compression methods that have pros and cons which are able to balance each other out.

Dean Edwards Packer

Dean Edwards packer can produce the smallest compressed javascript files without gzip compression. To get this smallest of sizes it removes comments, white spacing, renames variables, and even does Base62 encoding.

This method is great for shared hosts where they don't provide and you can't install compressors like mod_deflate and you aren't going to roll your own compression script with browser detection and all those little things it would need to do.

While packer is great it has two shortcomings to know about. Since it uses Base62 encoding your browser needs to not just download and read the file but also evaluate it. This evaluation takes time. I've seen it take anywhere from 100 milliseconds to 200 milliseconds for the packed version of jquery. So for example, if you are using a packed javascript that adds rounded corners to your page there may be a flash of the screen just after the page loads when the browser adds those corners because of the delay.

The second problem has to do with adding flash to pages via javascript in Internet Explorer. A common way to get around the click to activate problem in Internet Explorer is to have javascript insert the flash into the page. Packed javascript can't do this. It has to do with how IE evaluates the code.

YUICompressor

The YUICompressor is another powerful option. Teaming the YUICompressor with gzip compression produces smaller file downloads than packer (and even packer + gzip) and they don't suffer from the two packer shortcomings.

The YUICompressor on it's own does produce smaller files than jsmin but they are still slightly larger than packer. This is good to use if you have javascript manipulating the look of a page right at the time it loads or if you are manipulating flash in a page.

The YUICompressor does have a short coming. It is to slow to be recommended for on the fly code compression in your applications.

Conclusion

Most of the time packer gets the job done well. For shared hosts it's the way to go. If you are dealing with flash, javascript to affect the look of a page, or have access to something like mod_deflate the YUICompressor is great. Otherwise Dean Edwards Packer gets the job done pretty well.