1

Any HTML page in my project contains two types of images:

  1. Images that are system defined, such as the logo and icons and buttons
  2. User defined images such user's profile image, or company logo etc.

On a list page typically a combination of both type of images is rendered. Now what I want is, using Rails, that all the images are compiled onto one or two big sprites at runtime depending on list of user-images or list of icons/logos being rendered in the given page. By doing this, I can avoid using img tags and deeply nested anchors which would traditionally be there in outgoing html.

Sending user images via background CSS is X times faster than img tags, and let's me keep html/haml clean. Also it would be great if someone can also advise me caching issues when spriting in runtime? (If this thing exists, in the first place.)

Emil Vikström
  • 84,510
  • 15
  • 132
  • 168
Marvin Danig
  • 2,967
  • 5
  • 30
  • 56

1 Answers1

1

I don't know of a way to programmatically create sprites in Ruby. You might be able to use a library for image manipulation (perhaps FreeImage), but that seems fairly low level. Keep us posted if you find anything that can do this.

The CSS sprite is an image, so the usual caching rules for dynamically created images apply. If you're not careful, the browser will keep using a cached copy and the user will never see new versions of the sprite. A few ways to work around this are:

  • Use the cache-control HTTP header field to set a reasonable timeout value for the image. I've tried this approach, but couldn't get it working.

  • Give the image a unique name each time it is recreated. In this scenario, the image is set to never expire. If it is rebuilt, it is given a new name, causing the browser to make a new request for it. I've used this with success. Rails does the same thing with your stylesheets and javascript files.

  • Another option may be to use ETags. Each version is given a new, unique ETag and the browser uses this to determine if it should use a cached copy or get the latest. I haven't used this before, but it seems like it might fit your problem.

A related question on caching can be found here.

Community
  • 1
  • 1
Michael Venable
  • 4,852
  • 3
  • 21
  • 19
  • I came across a blog with a comment from @dhh that Rails 3.1 is going to "miss css spriting" this time. Not sure what that meant. But there’s this new ruby gem called active_assets, http://bit.ly/eRTwU4. It lets you generate sprites and the stylesheet for the sprite with a rake task. – Marvin Danig Jun 29 '11 at 14:37