Wednesday, January 20, 2010

Great resources for getting caching working on your rails app

I spent some time today getting caching of static assets up for a project I'm working on. Before picking a direction, I did a bunch of reading to understand different approaches. At the end of it all, the things I found most helpful were:

Stephen Sykes approach to getting Apache to automatically expire files that have the (automatically generated) timestamps that rails generates with image_tag, etc
his blog post

To test if that's working, you can use curl
curl --head http://yoursite.com/images/yourimage.png?1234567890
(as shown in this post that actually describes a different way of doing things that I didn't go with)

Once you've got caching of images from your erb files working, you can use YSlow to see your grade for Expires headers.

If you're still getting a poor grade for expires headers, it's probably because you have CSS that includes references to images.

In order to fix this, you basically want to append timestamps as query strings to the image URL's in your css file. There are two basic ways to do this.

One is to use controllers to generate your stylesheets from .erb files. This allows you to use the rails image_tag helpers. Since the resulting output files will be cached, this is pretty efficient. For details, see this blog post.

The second way (which I went with) is to use the very sweet plugin css-asset-tagger. This is described by it's authors Redline in this blog post. Basically, this works "automagically" to run through your css files after they are deployed on production and modify them by inserting timestamps after each image.

In either case, once the images in the CSS file also contain timestamps in the query strings, the expirations setup at the top will pick them up as well.

1 Comments:

At 9:12 PM , Blogger 開心唷 said...

This comment has been removed by a blog administrator.

 

Post a Comment

Subscribe to Post Comments [Atom]

Links to this post:

Create a Link

<< Home