Automatically Minimizing Javascript and CSS with Rails

If you obsess over your YSlow and/or Page Speed performance scores, you might be wondering how to get your Rails app to automatically crunch Javascripts and CSS files without actually requiring cumbersome rake tasks to be repeated during every deploy.  Fear not: you can quickly monkeypatch Rails to do this.

  1. Copy this gist into your lib/ directory.
  2. Create a config/initializers/javascript_minimization.rb as described here.
  3. Use your javascript_include_tag and stylesheet_include_tag helpers as normal, with the caching option turned on.
  4. Watch your users save 100kb.

About Patrick

Patrick is CEO over at Starfighter. Want to read more stuff by him? You should probably try this blog's Greatest Hits, which has a few dozen of his best articles categorized and ready to read. Or you could mosey on over to Hacker News and look for patio11 -- he spends an unhealthy amount of time there.

2 Responses to “Automatically Minimizing Javascript and CSS with Rails”

  1. Mohammad Abed September 12, 2010 at 9:53 pm #

    Have you taken a look Jammit http://documentcloud.github.com/jammit/

  2. Tarellel September 23, 2010 at 6:26 am #

    As Mohammad said you may wish to take a look at Jammit. I’ve used it on a few of my recent projects and it has the functionality (not limited to) to: gzip your JS/CSS files, as well as use the YUI or Google Closure Compilers to compress and optimize your files. It’s a rubygem so it can easily be setup with very little or not hassle