Foolproof Front-End Asset Cachebusting

Here’s a scenario you’re probably familiar with if you’ve done any amount front-end development. After deploying a CSS or JavaScript change and notifying the client, you hear back that they’re not seeing the updates. This is usually because their browser has the old CSS/JS cached and needs to be hard reloaded to re-download the new assets.

This isn’t too big of a deal for low-traffic sites or small changes, but what about when you’re deploying a significant change to a high-traffic site? I had a scenario recently where I was deploying a new header and navigation to a high-traffic website that had been using the old header styles for years. We’d rebuilt it from the ground up — new HTML, CSS, JS, everything — so without the new front end assets, the page looked completely broken.

Version Parameter

A common trick to force the browser to re-download assets is to add a version parameter to the query string of the CSS or JavaScript file you’re linking to:

Every time you make an update to the file, you’d update the version to a new value, which the browser reads as a new URL it must re-download to it’s cache. This is a pretty good solution, except that you have to remember to change the version every time you’re deploying updates that necessitate the browser re-download new assets.

Timestamp Versioning

One solution I’ve seen to this is using a timestamp as the asset version. This is especially helpful during development because it ensures you have the freshest version of the file on every page load:

While the timestamp method works well for development, but you wouldn’t want to use it in production since it forces the browser to re-download the assets on every page load — no bueno. Ideally we’d like a solution that only forces the browser to updates its cache when something changes, but makes use of the cache for performance reasons when it can.

File Modified Versioning

The solution is to set the version parameter to the timestamp of the last file modification for the asset you’re linking to:

Think about it — this solves all of our problems. Without any manual work, we’re guaranteed the browser will re-download our assets every time they change. And if they haven’t, the URL remains the same on as the last page load and the browser can keep its existing cache. Viola!

Integrating in WordPress

Since most of my work takes place in a WordPress environment, here’s how you’d integrate this using WordPress’s wp_enqueue_style() and wp_enqueue_script() functions:

Whatever you pass to the 4th parameter in both enqueue functions serves as the value for the ver parameter in the URLs to the asset files generated by WordPress.

Other Options

As is usually the case, CSS-Tricks has a great post listing a bunch of different methods to tackle this problem.

If you have a favorite solution, let me know in the comments.

Leave a Reply

Your email address will not be published. Required fields are marked *