Automatic cache busting powered by Git

Will Morgan
2 min readDec 31, 2014

--

I’ve been meaning to use Gulp for a while now — I’ve normally used Grunt for builds.

I decided to use Gulp to take care of builds for my single page personal website. So far I’ve been pleased with how much easier and expressive it is to set up builds, instead of getting bogged down with endless configuration hashes. It also has watch functionality out of the box, and appears to run faster, too.

After getting the usual CSS minification, JS uglification, asset concatenation, and autoprefixification out of the way, I needed to sort out some more resilient cache busting, because using query strings in URLs doesn’t always work.

Existing options

Looking at the available options, it looked pretty much like gulp-rev or its permutations was the only way to go.

However, NPM dependency trees quickly get out of hand. Also, the idea of a massive revision build step that generates manifest files is a bit overkill.

If possible, I wanted to avoid having build tasks mess with my HTML because that’d just introduce another layer of complexity, when all I really care about is good content and getting respectable results on Google PageSpeed. Also, it would be another item in a commit changeset, potentially polluting diffs and blames later down the line.

For a simple use case, this doesn’t have to be something that build tools have control over.

Git to the rescue

Using Git, it is possible to retrieve the current (HEAD) commit’s hash. That hash will change if you change branch or tag.

This means a build step will not be required if you change branch or pull, and this quirky frontend optimisation requirement is neatly tucked away behind the scenes.

How it’s done

As this is my single page website, it doesn’t use a framework. But the concept is still valid if you wish to use a templating language like Twig or Blade.

I’m using PHP and Apache for this, but the concept is really quite elementary:

  • Call git rev-parse HEAD, which will return you the commit’s full sha1 hash.
  • Include the file and assign the variable.
  • Append the hash variable to your combined file reference.
  • Add a rule to your server configuration that will perform a transparent redirect to the physical file.

Here’s a gist showing how.

Final words

  • The only caveat here is that the cache will be busted every time any code element in the site changes — but for a tiny site like mine with only one bundle, it’s not a massive concern.
  • Gulp is still awesome; if having an elegant build system was a requirement (perhaps for a client project), I’d be embracing its processes fully.
  • I imagine having such easy access to the git’s HEAD hash is useful for other purposes.
  • I am available for JS and PHP contracts in London, UK as well as remotely!

--

--

Will Morgan

Bicycle and drum and bass enthusiast; programmer with 15 years’ experience in running code on the wrong environment.