New Sep 17, 2024

How to dynamically load Web Components

Multi Author Blogs All from Go Make Things View How to dynamically load Web Components on gomakethings.com

Over the last year, I’ve converted all of my code bases over from traditional DOM manipulation or JS-rendered UI to mostly pre-rendered HTML and Web Components.

Today, I wanted to quickly show you how I automatically load the JS for my Web Components only on the pages where they’re used.

Let’s dig in!

The dynamic ES import() method

The import() method works like the import operator, but runs dynamically as a function. That means that you can run it conditionally.

In my code, I check to see if the custom element for my Web Component is present using the Element.querySelector() method. If it is, I can import() the script that power it.

if (document.querySelector('simple-toc')) {
	import('/path/to/simple-toc.js');
}

Because Web Components are self-instantiating, I don’t need to bother with waiting for the script to load, deconstructing specific methods, and running initialization scripts.

I can import it as a side-effects only module and get on with my day!

Here’s a demo on CodePen.

Quick aside: if you want to learn more about ES imports, side-effects only modules, or Web Components, join the Lean Web Club for free today.

This is a great general use solution, but I have another method I prefer even more.

Shortcode detection in Hugo

My personal projects are all powered by Hugo, a static site generator.

Hugo has the ability to check if a shortcode has been used on the current page, and render content in response.

I use shortcodes for all of my Web Components, like this…

{{<simple-toc heading="On this page...">}}

Then, in my footer, I can check if a shortcode is used and load the corresponding JavaScript file…

{{- if .HasShortcode "simple-toc" -}}
    <script src="/path/to/simple-toc.js"></script>
{{- end -}}

I like this approach a little better because it reduces a bit of the loading lag.

To make it even more performant, I actually use Hugo’s readFile command to inline the JS instead of loading it externally.

🎉 Preorder Getting Sh!t Done today and get 40% off! Be more productive, get more done, and feel more in-control of your work and life. Click here to learn more.

Scroll to top