前言#
最近在 Hugo 創建了幾個 Shortcode ,許多有導入 JavaScript,於是做了一個 Partial 範本方便以後快速使用。
Partial 範本內容#
在/layouts/partials下新增prevent-js-reload.html
{{/*
Usage: {{ partial "prevent-js-reload.html" (dict "Page" .Page "id" "script-id" "src" "js/script.js") }}
Optional: add "fromAssets" true to load from assets (resources.Get + Minify + Fingerprint).
Params:
- Page: the .Page object (required)
- id: unique key used to prevent loading the same script more than once per page
- src: path to the JavaScript file (relative to static/ or assets/)
- fromAssets: if true, load from assets pipeline instead of relURL
*/}}
{{ $id := .id }}
{{ $src := .src }}
{{ $fromAssets := .fromAssets | default false }}
{{ $scratchKey := printf "script-loaded-%s" $id }}
{{ if not (.Page.Scratch.Get $scratchKey) }}
{{ .Page.Scratch.Set $scratchKey true }}
{{ if $fromAssets }}
{{ $js := resources.Get $src }}
{{ if $js }}
{{ $js = $js | resources.Minify | resources.Fingerprint (.Page.Site.Params.fingerprintAlgorithm | default "sha512") }}
<script src="{{ $js.RelPermalink }}" integrity="{{ $js.Data.Integrity }}" defer></script>
{{ else }}
<script src="{{ $src | relURL }}" defer></script>
{{ end }}
{{ else }}
<script src="{{ $src | relURL }}" defer></script>
{{ end }}
{{ end }}



