css-caching-issueWhilst clicking around the internet, you decide to go back and visit one of your favourite sites and suddenly it all look broken: the layout seems wrong and it is just a mess. This is where clearing your cache or using the “shift and click refresh” trick normally fixes things and gives you a nice, fresh-looking site.

The solution we have come up with uses query string manipulation so the browser can quite happily cache the file in the normal way, however when the query string changes it will grab a new version thinking it is a dynamic file that has changed on the basis of the query string changing. The trick is to ensure the query string only changes when you update the cascading style sheets (CSS) file without you having to make any changes manually. The elegant solution we are starting to use at Zeta utilises the PHP function filemtime() to insert modification time of the CSS file into the query string.

1
<link href="css/style.css?v=<?php echo filemtime("css/style.css")?>" rel="stylesheet" type="text/css" />

In the finished HTML you get

1

When you update the CSS, the file modification time changes automatically and updates the query string for you, without you having to make any code changes.

The problem with cached CSS, where a browser is using an out-of-date local copy of a CSS file instead of requesting the latest-and-greatest version from the website, has been causing this issue for years.  Developers have come up with many different creative ways to try and prevent it and to some degree they have all fixed it, but there are normally some drawbacks with each solution.  For example, the requirement to change the name of the file every time you update the CSS, setting up redirects which involve an extra query from the browser on every page to request the style sheet, adding randomly generated query parameters or the need to run a global “search and replace” to ensure you update things across different pages and platforms sharing a CSS file; these can all make systems more trouble than they are worth, especially ones that prevent the CSS being cached at all.

We have looked at most of these solutions and considered all the downsides before coming up with what we consider to be “the definitive” solution to this problem, one which does not suffer from these downsides and makes it easy to just get on with the real business of updating your layout without having to unnecessarily change extra files just to make sure people see your lovely new layout.

We would love to hear of your experiences of CSS caching and what you have done to resolve this issue.

Google+

Comments

comments

This entry was posted in Blog and tagged , , . Bookmark the permalink.