Sub topic 5
Loading Code Only When It Is Needed
This chapter assumes you know ES module import/export syntax, promises with async/await, and the basic form of import() covered earlier: it takes a specifier and returns a promise for the module namespace object. The focus here is when to call it. Lazy loading means a module is fetched and evaluated only once the program actually needs it. Conditional loading means it is fetched only if some condition holds.
Why Defer Loading at All
A static import at the top of a file puts the imported module on the startup path. The runtime has to fetch, parse, and evaluate it before your entry module runs, even if the user never touches the feature it supports. A rich-text editor, a charting library, or an admin panel can easily add hundreds of kilobytes that most sessions never use.
Moving that dependency behind import() changes three things:
| Aspect | Static `import` | `import()` behind a trigger |
|---|---|---|
| When the network request happens | Before the importing module runs | When the trigger fires |
| Cost to initial load | Always paid | Paid only by users who need the feature |
| Latency at point of use | None, already loaded | One fetch and evaluation, unless prefetched |
| Failure surface | Whole module graph fails to link | One promise rejects, and the rest of the app keeps working |
The trade-off is in the third row. Lazy loading moves the cost from startup to the moment of use. Good lazy loading hides that cost by starting the load a little before it is needed.
Trigger 1: User Interaction
The simplest trigger is an event. The module is requested the first time the user asks for the feature.
const button = document.querySelector('#show-chart');
button.addEventListener('click', async () => {
const { renderChart } = await import('./chart.js');
renderChart(document.querySelector('#chart'));
});The second and later clicks do not refetch chart.js. The module map caches each module instance by its resolved URL, so later calls get the same namespace object. The await still yields to the event loop once, but no network work happens.
The cache stops duplicate loading. It does nothing about duplicate work. If a user double-clicks before the first load finishes, both handlers wait on the same pending load, and then renderChart runs twice. Guard the action itself when that matters:
const button = document.querySelector('#show-chart');
let rendering = false;
button.addEventListener('click', async () => {
if (rendering) return;
rendering = true;
button.disabled = true;
try {
const { renderChart } = await import('./chart.js');
renderChart(document.querySelector('#chart'));
} finally {
rendering = false;
button.disabled = false;
}
});Hiding the Latency: Prefetch on Intent
Users often signal intent before they click. They hover, focus with the keyboard, or touch the screen. Starting the import at that point usually gives a few hundred milliseconds of head start. To reuse the same in-flight request, wrap the import in a function that remembers its promise:
function lazy(loader) {
let promise = null;
return () => {
if (promise === null) {
promise = loader().catch((err) => {
promise = null; // allow a retry after failure
throw err;
});
}
return promise;
};
}
const loadEditor = lazy(() => import('./editor.js'));
const openButton = document.querySelector('#open-editor');
// Warm up on intent; ignore errors here, the click path reports them.
for (const type of ['pointerenter', 'focus', 'touchstart']) {
openButton.addEventListener(type, () => loadEditor().catch(() => {}), {
once: true,
passive: true,
});
}
openButton.addEventListener('click', async () => {
const { mountEditor } = await loadEditor();
mountEditor(document.querySelector('#editor-root'));
});The module map already deduplicates successful loads, so why wrap it? There are two reasons. The wrapper gives you one named place to change the specifier, and it controls retries. In browsers, a failed module fetch can stay recorded as failed in the module map for that specifier. Clearing your own cached promise at least lets you choose a retry strategy, such as a cache-busting query string. The chapter on import failures covers that in detail.
Trigger 2: Visibility
Content far below the fold does not need its code until it scrolls into view. IntersectionObserver reports when an element approaches the viewport, and rootMargin lets you start loading before it is actually visible.
const section = document.querySelector('#comments');
const observer = new IntersectionObserver(
async (entries) => {
if (!entries.some((entry) => entry.isIntersecting)) return;
observer.disconnect(); // load once
const { mountComments } = await import('./comments.js');
mountComments(section);
},
{ rootMargin: '300px 0px' }
);
observer.observe(section);Disconnecting before the await matters. If you disconnect after it, scrolling during a slow fetch can fire the callback again and mount the widget twice.
Trigger 3: Idle Time
Some modules are not tied to an element, but you still know they will probably be needed, for example an analytics client or a search index. Loading them when the main thread is idle keeps them off the critical path without making the user wait later.
const whenIdle =
'requestIdleCallback' in window
? (fn) => requestIdleCallback(fn, { timeout: 5000 })
: (fn) => setTimeout(fn, 2000);
whenIdle(async () => {
const { initAnalytics } = await import('./analytics.js');
initAnalytics({ endpoint: '/collect' });
});The timeout option makes sure the callback eventually runs on a busy page. Safari lacks requestIdleCallback, so the setTimeout fallback stands in for it.
Conditional Loading
Here the question is whether to load at all, not when. The condition is evaluated once, and only the branch taken pays for its module.
Feature detection and polyfills
Ship a polyfill only to environments that lack the feature:
async function ensureStructuredClone() {
if (typeof globalThis.structuredClone !== 'function') {
await import('./polyfills/structured-clone.js'); // side-effect import
}
}
await ensureStructuredClone();
const copy = structuredClone({ nested: { value: 1 } });
console.log(copy);The import result is ignored because the polyfill works by assigning to globalThis. The await on the call is still needed, so code that relies on the feature does not run before the polyfill has evaluated. (This snippet uses top-level await, which a later chapter explains. Inside a function, await ensureStructuredClone() works the same way.)
Environment and configuration
In Node.js, a command-line tool can load only the subcommand the user ran. Startup then stays fast no matter how many commands exist:
// cli.mjs
const commands = {
build: () => import('./commands/build.mjs'),
serve: () => import('./commands/serve.mjs'),
lint: () => import('./commands/lint.mjs'),
};
const [name, ...args] = process.argv.slice(2);
const load = commands[name];
if (!load) {
console.error(`Unknown command "${name}". Try: ${Object.keys(commands).join(', ')}`);
process.exit(1);
}
const { run } = await load();
await run(args);Mapping names to arrow functions that each contain a literal specifier has two benefits. User input cannot pick an arbitrary file, and bundlers can still see every possible target. Building the path straight from name would give up both. Computed specifiers get their own chapter.
The same shape works for user roles (load the admin panel only for admins), locales, and A/B variants.
Common Mistakes
Accidentally eager
A dynamic import placed at module top level, outside any trigger, still runs at startup. It saves no work, and it hides the dependency from tools that understand static imports:
// Not lazy: runs as soon as this module evaluates
const chart = import('./chart.js');Code is lazy only when the import() call sits inside something that runs later: an event handler, an observer callback, or a branch.
Lazy-loading what is always needed
If every page view calls renderHeader(), moving it behind import() adds a network round trip after startup and removes nothing from it. Lazy-load features that a real share of sessions never use, or that are large enough to delay first paint.
Waterfalls
If editor.js itself statically imports toolbar.js, which imports icons.js, the first click triggers a chain of sequential requests in an unbundled setup. Each one is discovered only after its parent is parsed. Bundlers flatten this into one chunk. Without a bundler, you can add <link rel="modulepreload" href="/editor.js"> hints, or start loads early with prefetch.
Forgetting the loading and error states
Between the trigger and the resolved promise, the UI should show that something is happening. If the promise rejects, the user needs a message and a way to try again. Leaving the button inert on a slow network looks like a broken feature.
Exercise
A page calls const { mountMap } = await import('./map.js') inside a click handler. Users report that clicking twice quickly creates two maps. Will map.js be downloaded twice? Explain why two maps appear, and give a fix.
Show answer
No. Both calls resolve to the same cached module instance, and at most one fetch happens. Two maps appear because both click handlers wait on that load, and each one calls mountMap after it resolves. Fix it by guarding the action: set a flag or disable the button before the await and reset it in a finally block, or check whether a map is already mounted before mounting.
Exercise
You have an IntersectionObserver callback that awaits import('./video-player.js') and then calls observer.disconnect(). On slow connections the player sometimes mounts twice. Why, and what is the minimal change?
Show answer
While the import is pending, the element can leave and re-enter the viewport, and the callback fires again because the observer is still connected. Move observer.disconnect() to before the await, right after confirming that an entry is intersecting.
Exercise
A CLI builds its subcommand path as import(./commands/${process.argv[2]}.mjs). Name two drawbacks compared with a map of name-to-loader functions that use literal specifiers.
Show answer
First, user input controls which file is loaded, so a value like "../secret" can reach files outside the commands folder. Second, bundlers and static analysis tools cannot reliably list the possible targets, so they may include too much, too little, or nothing. A third drawback is that unknown commands fail as a module-not-found rejection instead of a clear usage message.