coffee lover, dog person, frontend engineer

ProTip: A PHP Cache Buster for CSS + JavaScript Assets

Posted July 1st, 2016 in PHP tagged CSS, JavaScript

I know that it’s extremely rare for me to post about PHP… but hear me out.

I’ve worked with a few clients who will about halfway through their project receive link from me to get a first-look at their project in development. Throughout the project they’ll get updates from me about going back to this same development preview link, but the problem I have experienced is that their browser has previously cached (now stale) versions of the CSS and JavaScript files - meaning my client is seeing the latest HTML and markup, but stale CSS + JavaScript.

This does not make for an awesome start to a preview + status call.

Bust Those Caches

The easiest and quickest (and dirtiest?) solution I’ve found to remedy this issue is to use a PHP-driven UTC timestamp URL parameter cache buster on files which tend to be cached by my clients’ computers. Check it:

<link rel="stylesheet" type="text/css" href="path/to/stylesheet.css?r=<?php echo time(); ?>" />

<script type="text/javascript" href="path/to/javascript.js?r=<?php echo time(); ?>"></script>

That little <?php echo time(); ?> will barf out a UTC timestamp, ensuring the URL is always “unique” (enough) to bypass the browser’s cache and always pull the latest version.

The parameter name r bears no significance here - in this example it stands for “random,” but you could name that /?random= or /?cachebuster= or /?fhqwhgads= if you really wanted to.

You might not need this for all your clients - but it tends to be extremely useful for clients who might not know how to clear their browser cache.