3.2 KiB
+++ description = "Add 3rd-party dependencies to your site" title = "Extending Client Code" weight = 3 +++
Adding JavaScript or Stylesheets Unconditionally
If you simply want to add additional JavaScript files or CSS stylesheets on every page of your site, you can do so by either adding them in your layouts/partials/custom-header.html
or layouts/partials/custom-footer.html
partial.
Sometimes this just bloats up your site when only in a few cases those files are really needed. See the next section, on how to conditionally add those dependencies.
Own Shortcodes with JavaScript Dependencies
Certain shortcodes make use of additional dependencies like JavaScript and CSS files. The theme only loads these dependencies if the shortcode is used. To do so correctly the theme adds management code in various files.
You can you use this mechanism in your own shortcodes. Say you want to add a shortcode myshortcode
that also requires the jquery
JavaScript library.
-
Write the shortcode file
layouts/shortcodes/myshortcode.html
and add the following line{{- .Page.Store.Set "hasMyShortcode" true }}
-
Add the following snippet to your
hugo.toml
{{< multiconfig file=hugo >}} [params.relearn.dependencies] [params.relearn.dependencies.myshortcode] name = "MyShortcode" {{< /multiconfig >}}
-
Add the dependency loader file
layouts/partials/dependencies/myshortcode.html
. The loader file will be called from multiple locations inside of the theme with the parameterpage
containing the current page variable andlocation
with one of the currently defined locationsheader
: if called at the end of the HTMLhead
elementfooter
: if called at the end of the HTMLbody
element
{{- if eq .location "footer" }} <script src="https://www.unpkg.com/jquery/dist/jquery.js"></script> {{- end }}
Character casing is relevant!
- the
name
setting in yourhugo.toml
must match the key (that needs to be prefixed with ahas
) you used for the store in yourlayouts/shortcodes/myshortcode.html
. - the key on
params.relearn.dependencies
in yourhugo.toml
must match the base file name of your loader file.
See the math
, mermaid
and openapi
shortcodes for examples.
{{% notice note %}} If you are really into customization of the theme and want to use the dependency loader for your own locations, you can do this by simply calling it from inside of your overriden partials
{{- partial "dependencies.gotmpl" (dict "page" . "location" "mylocation") }}
{{% /notice %}}
React to Variant Switches in JavaScript
Once a color variant is fully loaded, either initially or by switching the color variant manually with the variant selector, the custom event themeVariantLoaded
on the document
will be dispatched. You can add an event listener and react to changes.
document.addEventListener( 'themeVariantLoaded', function( e ){
console.log( e.detail.variant ); // `relearn-light`
});