How to add signature in Assets (CSS/JS) files with GULP : Browser Cache Problem Solved

Tarikul Islam
Oceanize Lab Geeks
Published in
2 min readDec 29, 2017

Assets (css/js/image) are cached by browsers which is the more powerful features of web applications . But in development times its make curse for the developers. Because changing in assets file it’s immediately not reflecting which decrease the production time. For this problem we can avoid this circumstances in several way

  • Disabling browser cache (not recommended, because sometimes html page contain lot’s of images then the loading time will be more slower)
  • Add signature into the assets file. so that it’s loaded every time after any kinds of change

Add Signature into assets file with Gulp

For using this you should need to setup

const gulp = require('gulp');
const rev = require('gulp-rev');
gulp.task('default', () =>
gulp.src(['assets/css/*.css', 'assets/js/*.js'], {base: 'assets'})
.pipe(gulp.dest('build/assets')) // copy original assets to build dir
.pipe(rev())
.pipe(gulp.dest('build/assets')) // write rev'd assets to build dir
);

It will creates resources files with Hash signature like

build/assets/css/style-d41d8cd98f.css
build/assets/js/custom-d48fd41dd9.js
...

Now how we link this Assets into the file. Because it’s create new files every time of change. For this we will use manifest file for mapping

.pipe(rev.manifest())
.pipe(gulp.dest('build/assets')) // write manifest to build dir

By adding those code it’s create a mapping file named rev-manifest.json

{
"css/style.css": "css/style-d41d8cd98f.css",
"js/custom.js": "js/custom-d48fd41dd9.js"
}

Now we will make a funciton for linking this file. I am using PHP

public static function asset_path($filename) {
$manifest_path = 'path/to/rev-manifest.json';
if (file_exists($manifest_path)) {
$manifest = json_decode(file_get_contents($manifest_path), TRUE);
} else {
$manifest = [];
}
if (array_key_exists($filename, $manifest)) {
return $manifest[$filename];
}
return $filename;
}

Now we can use it easily into our files like

<link rel="stylesheet" media="all" href="build/css/<?= asset_path('style.css') ?>" /><script src="build/js/<?= asset_path('custom.js') ?>"></script>

Above code generate the links like

<link rel="stylesheet" media="all" href="build/css/style-d41d8cd98f.css" /><script src="build/js/custom-d48fd41dd9.js"></script>

--

--