/til/

2024 1219 Page-specific styles, scripts, and sprites

I stumbled upon a pattern recently that turned out to be very useful. It would be useful for any site that is built directly from the filesystem, but my sites and this example assumes Hugo.

  1. The Hugo template that contains my <head> element finds page resources for CSS, JavaScript, and SVG sprite files that have specific names. If they are present, I embed their contents directly in the page.
  2. I can create a file with those names any time I need styling, scripts, or sprites that are unique to a single page.

And that’s it! It’s especially useful when prototyping, but I’ve used it everywhere.

<style id="pagestyle">
{{- with .Page.Resources.Get "pagestyle.css" }}
{{ .Content | safeCSS }}
{{ end }}
</style>

<script id="pagescript" type="text/javascript">
{{- with .Resources.Get "pagescript.js" }}
{{ .Content | safeJS }}
{{ end }}
</script>

{{ with .Page.Resources.Get "pagesprites.svg" }}
{{ .Content | safeHTML }}
{{ end }}
content/
  blog/
    post-1/
      index.md
      pagestyle.css
      pagescript.js
      pagesprites.svg

You could do this with links instead of embedding the content directly. I figure that since these artifacts are be design only useful on a single page, there’s no need to load them separately to take advantage of caching, and there’s a small benefit of being certain they’ve loaded before the <body> by inlining them.

Responses

Webmentions

Hosted on remote sites, and collected here via Webmention.io (thanks!).

Comments

Comments are hosted on this site and powered by Remark42 (thanks!).