Caching CSS and JS with auto-timestamping

Probably the most challenging elements of a website to cache correctly are the CSS and Javascript files. Getting the user’s browser to cache these files is a massive speed boost…but it’s absolutely imperative that you can expire the file and deliver an update at a moment’s notice.

The only way to do this reliably is to version the filename, but it’s a real bind to have to update the filename every time it changes. If you’re storing your CSS/JS files in a content management system like SDL Tridion this can be a real PITA.

However, with a little help from our old friend URL rewriting it’s easy to do. Here’s how…

Publish your CSS file as normal:


Then in the tag, wrap the path with a server-side function call. This function grabs the timestamp from the file system and adds it to the filename, so the actual request made by the browser is:


Since this file doesn’t really exist, we need a rewrite rule that strips the timestamp and serves the contents of the original destination.

Now every time you update your file on the file system the server-side function will alter the timestamp and the browser will be presented with a new file to download.

Hey presto!