<p>At the end of <ahref="cache-busting">my last post</a>, 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 <em>only</em> 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.</p>
</span></span><spanclass="line"><spanclass="cl"> sed -i <spanclass="s2">"1s/.*/</span><spanclass="nv">$curr_mtime</span><spanclass="s2">/"</span> styles.mtime
</span></span><spanclass="line"><spanclass="cl"><spanclass="nb">echo</span><spanclass="s2">"file has been modified!"</span>
</span></span><spanclass="line"><spanclass="cl"><spanclass="c1">##insert the commit id</span>
</span></span><spanclass="line"><spanclass="cl"> sed -i <spanclass="s2">"s/css?=\w*/css?v=</span><spanclass="si">${</span><spanclass="nv">COMMIT</span><spanclass="si">}</span><spanclass="s2">/g"</span> index.html
<p>The key here is the command <code>stat</code>, 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.</p>
</span></span></code></pre></div><p>So all I have to do is write that unix timecode to a file (with our old friend <code>sed</code>), 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!</p>