Blog

CuTt4: Gulp cache busting

CuTt4: Gulp cache busting
Copper’s Tips & Tricks #4: Gulp cache busting

So, have you ever developed using Gulp? If you haven’t go do that now. Done? Good. One thing you may notice during normal development is that the browser refresh sometimes is not enough. You’ll definitely notice it when you deploy. That’s browser cache for you.

The easiest fix I’ve come up with so far, is to append a GET parameter to every js, or css file you use (here at the office we use a single compiled one instead of many), and what better to do this with other than the UNIX time?

/*
This CREATES or REPLACES a new file, which can be safely
ignored by Git so we don't have the annoying modified
functions.php file all the time.

You need to add the following to the functions.php file instead of
the usual DEFINE( "CACHE_BUSTER"...

include 'cache-bust.php';
*/

gulp.task( 'cache-bust', function() {
  
  var file = './path/to/wherever/cache-bust.php';

  require('fs').writeFileSync( file, "<?php\n"+
"DEFINE( \"CACHE_BUSTER\", "+Math.floor(Date.now() / 1000)+" );");

});

Finally, don't forget to include that new file, and append CACHE_BUSTER to the links to your css and js files (images rarely need this).

Happy cache busting!

Leave a Comment