How to include simple JavaScript within Hugo

bep's answer is excellent, but here are some additional details for hugo/frontend newcomers like me

1. Find a place in your HTML where to include the JS

First, one should copy the header.html or footer.html (or similar) of the Hugo theme to your layouts/partials folder. It does not necessarily have to be the header or the footer, but a file that is included in every page on your html (and that's why you would typically use the header.html or footer.html).

I got a theme that had the footer at <theme_folder>\layouts\partials\_shared\footer.html, which I then copied from the theme folder into the project layout folder <project_root>\layouts\partials\_shared\footer.html.

2. Include the script.js in the HTML

Then, I added to the bottom of footer.html

<script defer language="javascript" type="text/javascript"  src="{{ "/js/myscripts.js" | urlize | relURL }}"></script>

The defer attribute can improve the page loading time a bit, and "/js/myscripts.js" is the location of my javascripts. The location is path relative to <project_root>\static\. Here are the documentation about relURL and urlize.

The example script file contains just

// myscripts.js
function myFunction(x) {
    let d = new Date();
    alert("Current datetime: " + d + "\nYou passed in: " + x);
}

3. Use the JS function

This is an example of using the JS function from within Hugo template (any .html belonging to the template):

        {{ $somevar := "spam"}}
        <button onclick="myFunction( {{ $somevar}} )">Click me</button>

Inline JS

It looks like also inline JS runs just fine; for example, adding

<script>
    alert("Script loaded!");
</script>

to a template html file ran just fine. I would use this only for quick testing though, since some scripts might be needed in multiple html files, and adding the same script to multiple files would just increase your overall website filesize.


This depends a little on which theme you use. This may be an area where we could do a better job, but do this:

In the theme, look in the

layouts/partials folder.

If you find a header.html or similar, copy this to your local layouts/partials. You can then override the content of this file only. Alternatively you can customize by copying the template used for single pages, often: layouts/_default/single.html.