Where should page-specific JS go

Where do people usually write page-specific JS, in Hugo?

My partials have their own <script> tags, and the compiled source has various script tags throughout the page (rendered by different partials).

Is there a way to aggregate all my partial JS into a single <script> at the end of the page?

you can do it by hand …

for every script set a flag {{ $script1 := 1 }} in the partial (different names!)

at the end use a script partial with

{{ with $script1 }} < script … > {{end}}
{{ with $script2 }} < script … > {{end}}


I’d recommend using asset bundling as part of a pipes workflow.

Basically you want to keep your individual script files inside assests/js then slice these together and store in a variable. The you can create conditions based on what scripts you want to show on what pages. Check out this implementation here.

@regis has also written a great article on Hugo Pipes which should help steer you in the right direction.

1 Like