How to Dynamically Import a JavaScript Module
A guide on how to use dynamic import()
in TypeScript to load a JavaScript module on demand, using the Pagefind library as an example.
Sometimes you need to load a JavaScript library in the browser, but you only
need it for a specific feature. Instead of loading it on every page, you can use
a dynamic import()
to load it only when you need it.
This is great for things like search libraries, where you only want to load the code when the user actually opens the search box.
Use Case: Loading the Pagefind Search Library
Pagefind is a search library that runs in the browser.
When you build your site, it creates a /pagefind/pagefind.js
file. You don’t
need this file on every page, just on the pages that have a search feature.
Here is how you can load it dynamically when your search component is ready.
async function main() {
// The path to the library, relative to the public folder
const pagefindPath = "/pagefind/pagefind.js";
try {
// Use await with import() to load the module
const pagefind = await import(pagefindPath);
// Now you can use the library
pagefind.init();
console.log("Pagefind has been loaded and initialized.");
} catch (error) {
console.error("Failed to load Pagefind:", error);
}
}
document.addEventListener("DOMContentLoaded", main);
How it works:
-
const pagefind = await import(pagefindPath)
: This is the key part.import()
is a function that takes a path to a JavaScript module and returns a promise.await
pauses the function until the promise is resolved, which means the module has been downloaded and is ready to use.- The
pagefind
variable will then hold all the exported functions and values from that module.
-
Error Handling: It’s a good idea to wrap your dynamic import in a
try...catch
block. This way, if the script fails to load for some reason (like a network error), your whole site won’t break.