Minimise file size with the YUI Compressor TextMate Bundle

It’s quite obvious that the smaller the files that make up your website are, the less time your visitors will wait for them to download. One way of reducing file sizes is minimising JavaScript and CSS files by removing comments and whitespace, among other things.

To do that, you can either let the server do it for you or minimise the files yourself before uploading them to the server. Letting the server do it automatically is probably the most convenient way since you don’t have to remember to do it. But it isn’t practical or possible for everyone to use something like minify, so sometimes you’ll need to do it manually.

That may sound like more trouble than it’s worth. Luckily for us TextMate users there’s a handy YUI Compressor TextMate bundle that makes it almost as transparent as the server-side solution.

With the bundle (and YUI Compressor) installed, minifying your CSS and JavaScript files is just a keystroke away. The open file is compressed and saved in the same location as the original file, with “.min” added to the file name just before the file extension. Once you’re done, change the paths to your CSS and JavaScript files to point to the compressed versions.

If you don’t want to change the paths in your markup, you can also do what I’ve done on this site and use mod_rewrite to make the server send the compressed files instead of the originals. For each file you want to redirect, add a RewriteRule like this to your .htaccess file:

  1. RewriteRule ^css/main\.css$ css/main.min.css

You could also use the following to check that the minimised file actually exists on the server before redirecting to it (thanks to Chris Morrell for this tip):

  1. RewriteCond %{DOCUMENT_ROOT}/css/main.min.css -f
  2. RewriteRule ^css/main\.css$ css/main.min.css

All you need to remember is to recompress your CSS and JS files after changing them. There’s probably a way to make TextMate do that automatically, but I haven’t looked into it.

Again, the easiest way to minify CSS and JavaScript files is to have the server do it automatically. But when that isn’t an option this is a good alternative.

Posted on August 26, 2010 in CSS, Coding, JavaScript

Comments are disabled for this post (read why), but if you have spotted an error or have additional info that you think should be in this post, feel free to contact me.