When working on big JavaScript web apps, you can
split the bundle in multiple chunks and import selected chunks lazily, only when needed. That makes the main bundle smaller, faster to load and parse.
How to lazy import a module?
let hljs = await import("highlight.js").default;
is equivalent of:
import hljs from "highlight.js";
Now:
let libZip = await import("@zip.js/zip.js");
let blobReader = new libZip.BlobReader(blob);
Is equivalent to:
import { BlobReader } from "@zip.js/zip.js";
It’s simple if we call it from async
function but sometimes we want to lazy load from non-async function so things might get more complicated:
let isLazyImportng = false;
let hljs;
let markdownIt;
let markdownItAnchor;
async function lazyImports() {
if (isLazyImportng) return;
isLazyImportng = true;
let promises = await Promise.all([
import("highlight.js"),
import("markdown-it"),
import("markdown-it-anchor"),
]);
hljs = promises[0].default;
markdownIt = promises[1].default;
markdownItAnchor = promises[2].default;
}
We can run it from non-async function:
function doit() {
lazyImports().then( () => {
if (hljs) {
// use hljs to do something
}
})
}
I’ve included protection against kicking of lazy import more than once. That means on second and n-th call we might not yet have the module loaded so hljs
will be still undefined
.