Posts Tagged ‘CSS’

Forcing browsers to reload CSS

If you manage a decently high-traffic site, you will have run into the problem of needing to force your users’ browsers to reload your CSS files when you’ve made updates to them. I solve this by appending a query string to the end of the stylesheet’s href, so that this

1
<link rel="stylesheet" href="/css/master.css">

Becomes this:

1
<link rel="stylesheet" href="/css/master.css?foo=bar">

This forces the browser to reload the stylesheet because it sees that href and thinks that it’s an asset it doesn’t have cached. When it asks the server for it, the server has nothing it can do with the query, so the query is ignored and the stylesheet is served again.

I got tired of throwing random stuff on the end of the URLs though, so yesterday I wrote a Ruby script to do this for me, throwing a date/time stamp on the end of the href. The real one is customized for my particular site’s setup, but I’ve put the basics below so you can see how I handled it. I’m assuming that you’ve got an ID declared on the link element you want to mess with. Mine is called default-stylesheet.

Checkout the Gist of the script

I have a script like this on my webserver and I run it whenever I do major updates. The real one is augmented to allow you to pass arguments to act on staging or production. There are a million ways to set it up, but the basics above will be present in almost any approach.

Tags: ,