How to load some selected .js scripts on selected pages only

The classic way of managing javascript scripts is to load all your scripts in your footer/header.

But sometimes you have some pages with special .js scripts to load (caroussel, extra feature, whatever).
And you do not want your other pages/main page to be affected by this extra load.

You can choose what .js script to load on a page doing this : Using a partial on all your pages and some variables only where you want the .js scripts.

Your page frontmatter

In this example we suppose your scripts are in /assets/ folder.

url: myurl
js :
  - link : "plugins/lightbox2/dist/js/lightbox.min.js"
  - link : "plugins/mixitup/dist/mixitup.min.js"

Partial (on all your pages) for loading those “page specific” scripts

<!-- Iterate thru your page frontmatter -->
{{- $js := slice }}
{{- $jslocal := false }}
{{- range $.Params.js }}
  {{- $js = $js | append (resources.Get .link ) }}
  {{- $jslocal = true }}
{{- end }}

<!-- Create the .js really used -->
{{- if $jslocal }}
  {{ $nomscript := printf "js/script_%s.min.js" .Params.url }}
  {{- $scripts := $js | resources.Concat $nomscript }}
  {{- if $isProd }}
    {{- $scripts = $scripts | minify | fingerprint "sha384" }}
  {{- end }}
  <script src="{{ $scripts.RelPermalink }}" {{ if $isProd }}integrity="{{ $scripts.Data.Integrity }}"{{ end }} defer ></script>
{{- end }}

Nota : You can use this logic for your specific .css too.

1 Like

IMHO the proper solution is to automatically include the necessary js where it’s necessary. Usually js scripts are needed to show something or do something depending on the contents of the page; for example, you only want mermaid.js called on the pages where mermaid diagrams are. In this case the logical solution is to set a .Scratch variable somewhere in your mermaid shortcode, and then check if the variable is set in your footer and call mermaid.js based on that…

1 Like

This is if you suppose the page is a markdown page with shortcode.
And this is not my (and many others) use case.

And putting a variable in the frontmatter is exactly something depending on the contents of the page.

And what I propose is achieving to automatically include the necessary js where it’s necessary.

So I guess we are on the same line.

[EDIT] : If you want this in your .md pages with shortcode, you just have to adapt the script with something testing also a .Scratch. Best of both worlds

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.