Combine Multiple CSS/JS Files Into a Single File in Rails

File Cabinet (by juan23for)

One of the nice features in rails that many people overlook is the ability to combine multiple CSS or javascript files into a single file.  Why would you want to do this?  Well, it results in fewer HTTP requests being made by a client.  The end result is that the page will load faster in most browsers, and your YSlow score will be bumped up a bit.

How do you turn this feature on?  It is simple really; it just involves setting a single option in two rails helper calls which you're most likely already using.

If you ever took a look at the documentation for stylesheet_link_tag and javascript_include_tag, you may have noticed that there is a :cache option.  This option will basically tell rails to, instead of including all the files individually, combine them into a single file and include that in the HTML.  If you set :cache to true, it will set the name of the file to all.css or all.js.  If you set :cache to a string value (e.g. "foo"), then the file created will be that name (foo.js).

In order for this to work, ActionController::Base.perform_caching needs to be set to true in the appropriate environment's config file (by default, it is enabled for production but disabled for development).

Why the rails team decided to call the option "cache" instead of something like "combine_files" is beyond me, but I have a feeling that it is probably the biggest reason many people seem to not even know this feature is there.

Topics:

Comments: 1 so far

  1. Thanks for the tip Anthony. Helped me on my way.

    regards

    Greg

    Comment by Greg, Wednesday, January 7, 2009 @ 10:32 pm

Leave a comment

Powered by WP Hashcash

About Pathfinder

Follow the Blog

    Get a monthly update on best practices for delivering successful software.

    Subscribe via email

      

    Subscribe via RSS      RSS icon

Topics

Search

WordPress

Comments about this site: info@pathf.com