More cache-busting
Well, that was easy.
At the end of my last post, I had successfully written a script to stop stale CSS from getting stuck in the browser cache. It was a rough-and-ready solution — mine usually are — but it did the job. The one optimization I wanted to make was to ensure that the cache gets busted only when there is fresh CSS, as opposed to on every build. I had expected to get a nice long blog post out of this, but it turns out to be a very easy job.
Here is the new build script:
#!/usr/bin/env bash
prev_mtime=$(cat styles.mtime)
curr_mtime=$(stat -c %Y css/styles.css)
##has styles.css been modified?
if [[ $prev_mtime != "$curr_mtime" ]]; then
##update .mtimes
sed -i "1s/.*/$curr_mtime/" styles.mtime
echo "file has been modified!"
##insert the commit id
COMMIT="$(git rev-parse HEAD)"
sed -i "s/css?=\w*/css?v=${COMMIT}/g" index.html
fi
What?
The key here is the command stat
, which gives access to a load of useful data from the Linux filesystem. In this case, we’re getting the time last modified. Try it for yourself and see what comes back.
echo $(stat -c %Y foo.file)
1731532468
So all I have to do is write that unix timecode to a file (with our old friend sed
), then I can compare this value to whatever gets returned at build time, and only insert the Git id if the CSS has changed. Job done!