Numbers on stylesheet_link_tag and image_tag


#1

Can anyone explain to me exactly what are those numbers that rails
appends to stylesheets and images when using stylesheet_link_tag or
image_tag? At first I thought it would be so the browser wouldn’t
cache the stylesheets, but that doesn’t make much sense for images,
plus it seems that the numbers are unique, maybe based on the session.
Any idea?

Thanks


#2

The numbers in the url prevent the browser from caching images and
stylesheets. (Since it’s a different URL each time the browser assumes
they are different files.)


#3

The numbers in the url prevent the browser from caching images and
stylesheets. (Since it’s a different URL each time the browser assumes
they are different files.)

Actually, the numbers are there to make expiration easy while still
retaining maximum cachability.

So you setup your web server to cache all js, css, and images for 1
year. Now your users don’t have to spend precious sockets trying to
fetch all the assets on every page load. That means faster page views.

But how do you now let the user download new versions of the files you
just told his browser to cache for 1 year? That’s where the asset
magic number comes in. It’s actually a timestamp of the file.

So what you’ve done is say to the browser, cache forever the all.js
from 2006-12-12 (all.js?20061212). Now when you update all.js on
January 4th, the file will be linked up as all.js?20070104. To the
browser that’s a new file, thus it’ll fetch it again (and now save
that version for 1 year).

If you for whatever (crazy) reason do not want your users to cache
assets like this, you can set ENV[‘RAILS_ASSET_ID’] = “”. Then the
magic will be gone.


#4

So what you’ve done is say to the browser, cache forever the all.js
from 2006-12-12 (all.js?20061212). Now when you update all.js on
January 4th, the file will be linked up as all.js?20070104. To the
browser that’s a new file, thus it’ll fetch it again (and now save
that version for 1 year).

If you for whatever (crazy) reason do not want your users to cache
assets like this, you can set ENV[‘RAILS_ASSET_ID’] = “”. Then the
magic will be gone.

Thanks David, that makes a lot of sense. I was afraid the number was
random or fixed, and in both cases it would be no good, but using the
timestamp to refresh the file only when there’s a change is really
handy!