How to include custom JS in your Hugo theme
You can use the following code in your Hugo theme to include a range of custom Javascript files. This works similar to including custom CSS, see How to include custom CSS files.
You need to include it somewhere in the HTML <body>
. Depending on the situation, include it on the top, after the <style>
tags, but I recommend to include it at the end of the <body>
(i.e. just before </body>
) to ensure that the page is fully loaded before the scripts are executed (this will improve the page load time).
In my theme tailbliss
, it can be added to the end of themes/tailbliss/layouts/partials/footer.html
:
<!-- Custom JS code-->
{{ range $customJS := .Site.Params.custom_js }}
{{ $built := resources.Get $customJS | js.Build }}
<script type="text/javascript" src="{{ $built.RelPermalink }}" defer></script>
{{ end }}
Now you can configure a list of custom JS files in hugo.yaml
:
params:
custom_css:
- 'js/myscript.js'
Place the files in e.g. assets/js/myscripts.js
. The path in the hugo config file is relative to the assets
directory.