Last active
March 28, 2019 03:52
-
-
Save cmeza/e5488609d09722bd2c82e954859f36cf to your computer and use it in GitHub Desktop.
Gulp generate a cache busting random string
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var gulp = require('gulp'); | |
var fs = require('fs'); | |
var randomStr = require('randomstring'); | |
// pick where you want the file to land | |
var destinationDir = '.'; | |
// remove the file each time before generating a new one | |
gulp.task('clean-cache-buster', function() { | |
return gulp.src([destinationDir + '/cache.buster']) | |
.pipe(clean({force: true})); | |
}); | |
// generate a random string used for cache busting | |
// Our PHP reads that file to append for the '?v=<string>' on the css/js includes | |
gulp.task('bust-cache', ['clean-cache-buster'], function () { | |
// generate a random number between 5 - 10 | |
var randomNumber = Math.floor(Math.random() * 6) + 5; | |
// generate a string the length of the randomNumber | |
var randomString = randomStr.generate(randomNumber); | |
// write the value to a file where PHP can read | |
fs.writeFileSync(destinationDir + '/cache.buster', randomString); | |
}); | |
gulp.task('default', ['bust-cache', 'other-tasks-here']); | |
/* | |
PHP Usage | |
$cacheBuster = file_get_contents("/path/to/cache.buster"); | |
<link rel="stylesheet" type="text/css" href="/path/to/style.css?v=<? echo $cacheBuster; ?>"> | |
<script src="/path/to/file.js?v=<? echo $cacheBuster; ?>"></script> | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment