What is the best fix bundling js on page level?


{{- $fileName := .Slug | default .Title | urlize -}}
{{- if or (.IsHome) (eq .Layout "tool") -}}
    {{- $fileName = .Site.LanguageCode -}}
{{- end -}}

{{- $jsFiles := slice "main.js" "trending-api.js" "sw.js" -}}

{{ if .IsHome }}
    {{- $jsFiles = $jsFiles | append "api.js" "download.js" "zip.js" -}}
{{ end }}

{{- $jsLoc := slice -}}

{{ range $jsFiles }}
    {{ $jsLoc = $jsLoc | append (resources.Get (printf "/assets/js/%s" .)) }}
{{ end }}

{{- $mdName :=  $fileName -}}
{{- $jsName := printf "assets/js/%s.js" $mdName -}}

{{- $concatBundle := $jsLoc | resources.Concat "assets/js/bundle.js" -}}
{{- $processedBundle := $concatBundle | resources.ExecuteAsTemplate $jsName . -}}
{{- $finalBundle := $processedBundle -}}

<script src="{{ $finalBundle.RelPermalink }}" defer></script>

Please tell me the best solution to this. It’s not appending the js on homepage.

I may not fully understand your question, but In the baseof.html you could add a “block”.

{{- block "foot" . }}{{- end }}

And then under layouts/specific-page/single.html you could add something like:

{{ define "foot" }}
  {{ $customJS := resources.Get "js/custom.js" }}
  {{ $pageJS := slice $customJS | resources.Concat "js/custom-bundle.js" | minify }}
  {{ $pageSRI := $pageJS | resources.Fingerprint "sha384" }}
  <script defer src="{{ $pageSRI.RelPermalink }}" integrity="{{ $pageSRI.Data.Integrity }}"></script>
{{ end }}

This would allow you to have an optional Javascript include you only use on pages you want, without adding it to the main JS for the site.

Hugo block: block
Note this post if you are working with baseof.html and layouts on the newest version of hugo: New template system in Hugo v0.146.0

Your code snippet is out of context. So no way to detect you problem. so you might have

  • a context problem
  • a layout problem
  • cache problem
1 Like