Mad, Beautiful Ideas
Minifying JavaScript and CSS with GNU Make

At Yahoo! the Exceptional Performance team, has posted a series of guidelines for scalable, performant websites. Unfortunately, this is the only major web company I've encountered to date who has codified these suggestions in this fashion, but if you look over the companies who's primary business is the Web, you'll see the majority of these practices. If you want to test your own sites, Yahoo! made available the excellent YSlow, which plugs directly into Firebug.

One of the key suggestions is to minify all your JavaScript and CSS. This serves the primary purpose of making the JavaScript as small as possible for sending down the wire. Additionally, it might improve the speed of interpretation of the JavaScript and CSS, but that difference will be negligible and hardly worth noting. Luckily, Yahoo! has also released a tool for this.

The YUI Compressor is a Java application built on top of Rhino. The Compressor processes the JavaScript and CSS files and produces a far smaller version for distribution over the network. Most of the time, I've seen between a 20 and 50% reduction in filesize, and that's before applying gzip. Not bad at all.

The biggest problem I've had is that the YUI Compressor was not designed to batch together a bunch of files. I use a syntax-highlighter script for code samples on this site, but I found that it was larger than I needed. Needing to compress the JavaScript, I chose to use my familiar GNU Make to automate the process.

When I say familiar, I'm being a bit facetious. I've written Makefiles before, but GNU Make knows how to build certain types of files, and I've never had to told it how. Luckily, it's fairly simple:

This runs the YUI Compressor (from the path saved in JSMIN), with a JavaScript file as it's argument, and the file with a MINSUFFIX (I use -min, like YUI does). Now, when I build a rule like this:

        MINS=${SRCS:.js=${MINSUFFIX}.js}
        
        minify: ${MINS}
        

All the JavaScript files get minified, but only if they've changed. I pair this up with a method that concatenates the files after minification, but that's optional. The rule for CSS is almost identical, just replace .js with .css actually.

It's important in building applications to keep in mind the need for an automated build process. GNU Make works great for this, if you're on Unix. Even though JavaScript is an interpreted language, a simple compilation step, like YUI Compressor, goes a long way to improving the performance of the website overall. Automating this process makes deployment much easier, and is therefore worth pursuing. The above Make rule should help, not only with 'compiling' JavaScript, but with using Make for other languages that it doesn't support natively.