Best way to include JavaScript libraries in Hugo sites

Yet another option: supporting JS/CSS includes in your template based on frontmatter variables. This would allow you to use CDN links so you could forego including the libraries in your source code all together if you like. Otherwise you can use relative links if you want to drop the javascript or CSS files in your static directory.

Frontmatter

---
title: Some catchy title
js: https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.2/photoswipe.js
css: https://cdnjs.cloudflare.com/ajax/libs/photoswipe/4.1.2/photoswipe.css
---

Template partial

You could also support multiple includes if you want to provide scripts as an array in your front matter; you’d just loop through and add a script tag for each entry under js. The same process works for CSS.

CSS Partial

{{ if .Params.css }}
<link rel="stylesheet" href="{{ .Params.css }}">
{{ end }}

JS Partial

{{ if .Params.js }}
<script src="{{ .Params.js }}"></script>
{{ end }}
8 Likes