Jun 16, 2010 5
Setting Things Up
It’s incredibly easy to compress files and I’m going to outline the steps. The first thing you need to do is download Java. Since the Closure Compiler comes in the form of a .jar binary file, you’ll need Java to run it. Also, I’d recommended ensuring that you make Java available via your OS path so that you don’t need some long, convoluted command line statement to get to it.
Next, download the Closure Compiler .jar file and drop it into a convenient place that’s easily accessible.
For this tutorial, I’m going to use the uncompressed version of jQuery since it’s sizeable and will be a good sample to use to demonstrate the results. Uncompressed, that file comes in at 161kb. Note, though, that jQuery already comes packaged in a compressed, ready-to-use form via the jQuery website and I’m only using the file for demonstrating file compression.
Compressing the Code
Actually compressing the code is incredibly easy. Note that I’m using Windows so the steps will differ a little if you’re using OSX with terminal.
Next, run the following command to run the Closure Compiler:
java -jar compiler.jar –js=jquery-1.4.2.js –js_output_file=jquery-1.4.2-compressed.js
This will run the compiler and create a new, compressed version of the .js file. The results are immediately obvious:
jQuery Uncompressed: 161kb
jQuery Compresse: 71kb
Shaving off more than 50% of the file size is a REALLY big savings when your users initially come to the site and you want them to get snappy pages.
I would highly encourage you to check out the other compressors available to determine which one works for you. In a recent post I made outlining a list of tools I think are really important to client-side development, I mentioned the following:
For example, when I ran those tools on the same uncompressed jQuery file, here’s what I got:
YUI Compressor: 78kb
Microsoft’s Ajax Minifier: 72kb
Dojo Shrinksafe: 86kb
I tried using Packer and an online version of JSMin but I think the size of the file caused them both to timeout so I don’t have figures for you.
Again, it’s important that you do your own homework as there may settings that I’m not leveraging and could offer even better compression. If you find better performance, let me know. I’d love to hear about it.