0

I want to be able to loop through my views, particularly my main layout and apply a query string cache buster to our CSS and JS calls as follows:

<link rel="stylesheet" href="/assets/css/style.css?v=1234567" />

2

There are many methods, but since we build Helix projects with gulp one option is to leverage gulp to perform this action automatically.

At the top of your your gulpfile.js, require these modules:

var uniqId = require('uniqid');
var cacheBust = require('gulp-cache-bust');

Install these npm modules.

Then build the function:

var reviseAssets = function() {
    var versionNumber = uniqId();
    var viewPaths = [
        /* This can contain more than one path */
        config.websiteRoot + "/Views/**/Layout"
    ];

    return gulp.src(viewPaths)
        .pipe(debug({ "title": "Appending cache bust hash:" }))
        .pipe(cacheBust({ type: 'constant', value: versionNumber }))
        .pipe(gulp.dest(config.websiteRoot + '/Views'));
};

Call the function from inside of a task:

gulp.task("Revise-Assets", function (callback) {
    return reviseAssets();
});

You can then call this task in your release build task.

One way of making this better would be to have fewer module dependencies and to generate the version number based on a hash of the file contents. This way, new version numbers will only be generated if the file has changed.

This method would leverage browser caching and end users would not have to re-download your assets after every build.

This would also lighten the load on your CDN (assuming you have query string caching enabled) because the CDN wouldn't need to store as many versions of those assets.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.