I used to use Dean Edwards Javascript Packer a lot to compress my Javascript sources. Libraries of 100kB could easily shrink to 30kB and that saves load times & bandwidth. A good writeup by Julien Lecompte made me realize that there were better ways.

Javascript Compressors

Packer is an awesome utility that actually compresses code just like e.g. rar would. Only then let Javascript unpack the compressed string and execute it with eval. The file sizes of packer where always tinier than other utilities like jsmin, because jsmin just strips whitespace, etc. The advantages of jsmin where of course that it respects your original code better. And there's no time wasted in decompressing, jsmin results can be interpreted directly.

In short, the article Gzip Your Minified JavaScript Files changes the advantages & disadvantages between the compressors. Gzipped jsmin files are just as big as gzipped packer files. But because packer files have to be decompressed by Javascript, the packer file in the end is slower than the jsmin file which can be executed right away.

Okay, so letting your webserver & browser handle compressing & decompressing is faster then letting Javascript do it. It does not only save you bandwidth, it also makes the user experience snapier. And jsmin has better performance than packer. Sounds reasonable right?

So first step is to jsmin your original Javascript files. That's easy.

Second step is to enable automatic compression. Well that's pretty easy too.

Enable mod_deflate

I'm using Apache on Linux. Usually the Apache module: mod_deflate will be enabled by default. If not you have to enable it like this:

$ a2enmod deflate
$ /etc/init.d/apache2 force-reload

Instructing Apache What to Compress

Next we need to tell the webserver what file types need to be deflated. This can be done by either:

  • creating an .htaccess file in your webroot, OR:
  • modifying your VHost

Some people argue that configuration in the VHost is better because it saves your server the disk IO of accessing the .htaccess file with every request. But for VHost configuration you will need to be admin of your server, and an .htaccess file is as easy as uploading one with FTP. You choose.

Enter the following lines in one of the above files. And why not compress/deflate HTML, XML & CSS while we're at it?

# Compress Output
AddOutputFilterByType DEFLATE text/html text/css text/plain text/xml application/x-javascript
BrowserMatch ^Mozilla/4 gzip-only-text/html
BrowserMatch ^Mozilla/4\.0[678] no-gzip
BrowserMatch \bMSIE !no-gzip !gzip-only-text/html

The browser specific exceptions are necessary for compatibility.

Save the file, optionally (in the case of vhost) reload the apache config, and your files are now compressed on the fly! Do you notice the difference?