Sunday, February 03, 2008

Minify Rails Javascript and CSS with YUI Compressor

Here is a simple rake task to minify your javascript and css in a rails application using the YUI Compressor. You will need to have java set up correctly on the system and have the YUI Compressor jar in the lib directory of your Rails application to run this code.



You could drop this in lib/tasks/minify.rake and run it when deploying to production. If deploying with Capistrano, you might put it in the :after_update_code task:



This technique should work fine with Rails asset caching (explained here by the guys at maintainable software). Couple that with gzip compression by your web server and you should get dramatically reduced download times for your javascript and CSS.

A couple of caveats --

First, some javascript may not minify without problems. For example read this post by Andrew Dupont which talks about compressing prototype. I didn't seem to have a problem using the YUI Compressor with prototype but I haven't thoroughly tested it yet.

Second, I would prefer if the code above placed the minified version in different output directories. (Primarily so you don't accidentally check your minified versions into your SCM system.) Originally I did this putting the minified code in public/javascriptx and public/stylesheetx, respectively. Then I looked into how to get rails to easily look in different directories for javascript and css files. I found the JAVASCRIPTS_DIR and STYLESHEETS_DIR constants and thought I was all set -- then I then ran into the problem that changing:



in an initializer didn't really work as expected. Due to what looks to me like a bug in Rails 2.0 the files are still fetched from the original locations in spite of changing these constants - so I decided to stop messing with it and watch the Super Bowl.

If you don't like messing with Java to do something like this and are only concerned with compressing javascript then I would recommend reading this article by the guys at maintainable software. They give an example of using jsmin.rb for javascript minification.

3 comments:

  1. sweetness. now if we just had an all ruby CSS compressor. That would be nice, too.

    ReplyDelete
  2. actually just found one on the comments to http://betterlogic.com/roger/?p=309

    ReplyDelete
  3. A simple online javasdcript minifier can be found at http://netspurt.com

    It is based on dojo

    ReplyDelete