clear the css cache
So on this site I sometimes change the stylesheet. But whenever a browser has seent the file ones it may decide to cache it forever. So I decided to do something about it. The most obvious way to solve it is to make sure that the styletsheet file has a different name whenever it changes (or - as in this case - when there is a new version). A good unique thing to use here is the version hash from the git repo. I decided to go for the naming schems stylesheet.<hash>.css
. For example stylesheet.2bbcf48.css
As the faithful reader already knows I use nanoc to generate this static website and it turned out that I only needed to change two things.
First off the Rules
file. This is where to define how different files are generated based on the content. For all file types that don’t change in generated form there is the simple rule at the end of the file:
compile '/**/*' do
write item.identifier.to_s
end
This makes sure to write all files that are not treated elsewhere just as they are to the output folder. All binary files makes sense to include here. To treat css differently we need another rule for that:
compile '/**/*.css' do
git_hash = `git rev-parse --short HEAD`.chop
write "#{item.identifier.to_s[..-5]}.#{git_hash}.css"
end
Thanks to ruby this can be done in this compact way. (Just imagining doing this in Javaish….) Ruby treats antything between bakticks as calls to the command line. rev-parse --short
is a nice way to get the hash of the current commit. And indexing with a range is perhaps not that readable but it is fun and here it is quite easy to understand what it does. Just chop off the 4 last characters of the incoming file name. Then add hasn and suffix and done deal.
I thougt about putting the file name code in common code but since it was only two lines I decided against. The other place where a change was needed was of course the layout file where the css is used. In my setup here it is still in the default layout used by everything on the site. It is only <head>
stuff in there now.
/ style is style
- css_path = "/stylesheet.#{`git rev-parse --short HEAD`.chop}.css"
link rel="stylesheet" href="#{relative_path_to(css_path)}"
Using slim (since it is nice to be able to look at code and not die). You’ll recognize the same code to generate the file name just inlined a bit differently. And then it is added as the stylesheet of the site. Quite neat!
written by fredrik at 2025-01-06
More content on nanoc
More content on ruby