I’ve recently read up on the importance of site performance for search engine optimisation (SEO).

Google is saying that this year (2010) it may start using the speed your site loads as a factor in determining where your site shows up in its results list.

One great way of decreasing the load times of your site is to compress the CSS and Javascript.

Uncompressed Javascript File
Compressed Javascript File

There are several methods out there, but Yahoo’s YUI Compressor is supposed to be the best.
The compressor is a java (.jar) file that you need to run from the command prompt or terminal. The biggest flaw in it’s design is that you can only compress one file at a time.

Here comes the solution!

I’ve created a small bash script (.sh) that you can double click to convert all the javascript / css files in a folder (and all folders recursively)

here it is:

for file in `find . -name "*.js"`
echo "Compressing $file …"
java -jar min.jar --type js -o $file $file

The file’s pretty self explanatory; it finds all the files ending in .js (you can change this to .css for CSS files) and performs the compress action on each file.

To get this to work, you must make the script executable (download mine at the end of this post) and have the YUI Compressor file in the same directory as the batch.sh script (note that it needs to be called min.jar)

From terminal, you just need to go to the directory with the javascript files in and type
to run the script.
YUI Compressor compressing javascript files in a folder

et voila!

Update – an ever better option

If you put the batch.sh file in your /usr/local/bin folder then you’ll be able to use the command anywhere from within terminal (it must be chmodded a+x) I’ve made a file called ‘yuicompress’ which means, if placed in the /usr/local/bin folder (you need root access) you can type ‘yuicompress’ in terminal to get the command to work!


yuicompress arg

where arg is either ‘css’ or ‘js’ (no quotes) to compress CSS or JavaScript respectively.
The one thing you need to do with this new script is place the min.jar (or compressor.jar as I’ve renamed it) in a global place. I chose ~/Library/Application Support/YUICompressor/compressor.jar

Download the files below and place the yuicompress in /usr/local/bin, and the YUICompress folder in ~/Library/Application Support/YUICompressor/compressor.jar to get this to work from any older on your Mac/Unix box 🙂

Script: Batch Convert for YUI Compressor
YUI Compressor: YUI Compressor .jar file
Chmodded yuicompress script & YUICompressor folder: