From 447a2e160014c7fd74b404800185bfedd7597540 Mon Sep 17 00:00:00 2001 From: Rohan Kumar Date: Thu, 28 Mar 2024 00:16:48 -0400 Subject: [PATCH] New note: short cache busting fingerprints --- ...hort-cache-busting-fingerprints-in-hugo.md | 54 +++++++++++++++++++ 1 file changed, 54 insertions(+) create mode 100644 content/notes/short-cache-busting-fingerprints-in-hugo.md diff --git a/content/notes/short-cache-busting-fingerprints-in-hugo.md b/content/notes/short-cache-busting-fingerprints-in-hugo.md new file mode 100644 index 0000000..97a5316 --- /dev/null +++ b/content/notes/short-cache-busting-fingerprints-in-hugo.md @@ -0,0 +1,54 @@ +--- +title: "Short cache busting fingerprints in Hugo" +date: 2024-03-28T00:16:48-04:00 +replyURI: "https://github.com/gohugoio/hugo/issues/6241" +replyTitle: "Shorter fingerprinting (Hugo issue 6241)" +replyType: "DiscussionForumPosting" +replyAuthor: "XhmikosR" +replyAuthorURI: "https://github.com/XhmikosR" +--- + +I use a quick `crypto.FNV32a`-based fix for short cache-busting fingerprints that doesn't directly rely on the unstable `.Key` method. + +{{}}{{}} + +I use Hugo's `crypto.FNV32a` to generate a short hash, then copy the resource to a new path with that fingerprint. + +{{}} + +```figure +{{ $resource := resources.Get . -}} +{{- $target_path_formatStr := (replaceRE `(\.[^\.]*)$` ".%d$1" .) -}} +{{- $cacheBuster := $resource.Content | crypto.FNV32a -}} +{{- $target_path := printf $target_path_formatStr $cacheBuster -}} +{{- return resources.Copy $target_path $resource -}} +``` + +{{}} + +{{}}{{}} + +You can [see it used in my site's head element](https://git.sr.ht/~seirdy/seirdy.one/blob/master/layouts/partials/head.html). I invoke it using `partialCached` so the fingerprinting only happens once per resource: + +{{}} + +```figure +{{ $icon_svg := partialCached "cache-bust.html" "/favicon.svg" "/favicon.svg" }} +{{- printf `` $icon_svg.RelPermalink | safeHTML }} +``` + +{{}} + +{{}}{{}} + +Here's a snippet of the final rendered result: + +{{}} + +```figure + +``` + +{{}} + +Encoding it to a higher base and using alphanumerics could shave off 1-2 ch.