When developing a website, we will be updating a CSS stylesheet very frequently. However, due to caching by the browser, the newest styles are not always loaded. How can you force the browser to read the latest version of the stylesheet?
There are a number of suggestions I’ve read.
- Rename the stylesheet every time you update it. This undoubtedly works, but is a pain in the butt.
- Use PHP to place “cache-control” and “expires” headers in your document. These theoretically tell the browsers when they should look for new versions of the page, and if you set the dates to the past, the browser should always load a fresh version of the page. In my experience, though, this doesn’t force the stylesheet to be reloaded.
- Force a reload in Firefox by hitting “shift-reload”. This does force the html to be re-rendered, but in my experience does not force the stylesheet to be reloaded. And, it obviously only helps if you’re using Firefox!
Here’s the one thing that does work: use PHP (or whatever parallel command you have at your disposal) to add a meaningless yet oh-so-handy date query string to the URL for your stylesheet. In other words, if your styles are in a file referenced at http://example.com/styles.css, it will now look like this http://example.com/styles.css?d=123456789.
The server will ignore the string attached to the end of that url, but to the browser, this looks like a brand new stylesheet has been requested, and will no longer use the cached version of the stylesheet.
I develop in PHP, so I use the time() function to append a UNIX timestamp to the end of the url. In practice, then, a sample css tag in your document head will look like this:
<link rel="stylesheet" type="text/css" href="http://example.com/css/screen.css?d=<?php echo time(); ?>" />
I hope this helps solve a common development headache for you.