diff --git a/content/posts/cache-busting-2.md b/content/posts/cache-busting-2.md new file mode 100644 index 0000000..dee180a --- /dev/null +++ b/content/posts/cache-busting-2.md @@ -0,0 +1,39 @@ ++++ +date = '2024-11-15T22:33:10+01:00' +draft = false +title = 'More cache-busting' +tags = ['linux','CSS'] ++++ + +**Well, that was easy.** + +At the end of [my last post](cache-busting), 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: +```bash +#!/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. +```bash +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! +