How can I test caching and cache busting?
- by Nathan Long
In PHP, I'm trying to steal a page from the Rails playbook (see 'Using Asset Timestamps' here):
By default, Rails appends assets'
timestamps to all asset paths. This
allows you to set a cache-expiration
date for the asset far into the
future, but still be able to instantly
invalidate it by simply updating the
file (and hence updating the
timestamp, which then updates the URL
as the timestamp is part of that,
which in turn busts the cache).
It‘s the responsibility of the web
server you use to set the far-future
expiration date on cache assets that
you need to take advantage of this
feature. Here‘s an example for Apache:
# Asset Expiration
ExpiresActive On
<FilesMatch "\.(ico|gif|jpe?g|png|js|css)$">
ExpiresDefault "access plus 1 year"
</FilesMatch>
If you look at a the source for a Rails page, you'll see what they mean: the path to a stylesheet might be "/stylesheets/scaffold.css?1268228124", where the numbers at the end are the timestamp when the file was last updated.
So it should work like this:
The browser says 'give me this page'
The server says 'here, and by the way, this stylesheet called scaffold.css?1268228124 can be cached for a year - it's not gonna change.'
On reloads, the browser says 'I'm not asking for that css file, because my local copy is still good.'
A month later, you edit and save the file, which changes the timestamp, which means that the file is no longer called scaffold.css?1268228124 because the numbers change.
When the browser sees that, it says 'I've never seen that file! Give me a copy, please.' The cache is 'busted.'
I think that's brilliant. So I wrote a function that spits out stylesheet and javascript tags with timestamps appended to the file names, and I configured Apache with the statement above.
Now: how do I tell if the caching and cache busting are working?
I'm checking my pages with two plugins for Firebug: Yslow and Google Page Speed. Both seem to say that my files are caching: "Add expires headers" in Yslow and "leverage browser caching" in Page Speed are both checked.
But when I look at the Page Speed Activity, I see a lot of requests and waiting and no 'cache hits'.
If I change my stylesheet and reload, I do see the change immediately. But I don't know if that's because the browser never cached in the first place or because the cache is busted.
How can I tell?