Sub topic 5
Loading Code Only When It Is Needed
This chapter assumes you know how import() returns a promise for a module namespace object, and that you are comfortable with async/await and event listeners. Here you will apply import() to two common jobs. Lazy loading delays a module until the user needs it. Conditional loading fetches a module only when a runtime check says it is required.
Why Defer Loading
With static imports, every module in the graph is fetched, parsed, and evaluated before your entry module runs. A chart library, a rich text editor, or a date-picker can add hundreds of kilobytes. Many users never open those features. Loading them up front slows the first render, and nobody gets anything for the cost.
When you move such a module behind import(), you take it out of the startup path. The browser fetches it at the moment the code asks for it.
Lazy Loading on User Action
The most common trigger is a user action such as a click, opening a tab, or scrolling a section into view.
const button = document.querySelector('#show-chart');
button.addEventListener('click', async () => {
const { renderChart } = await import('./chart.js');
renderChart(document.querySelector('#chart'));
});The first click fetches and evaluates chart.js. Later clicks resolve right away because the runtime caches the module instance by its resolved URL. The module's top-level code runs only once.
Avoiding a Visible Delay
The first click still has to wait for the network. Two techniques help:
- Show loading state. Disable the button or show a spinner while the promise is pending.
- Preload on intent. Start the import on
pointerenterorfocus, so the fetch is usually finished before the click.
const button = document.querySelector('#show-chart');
let chartModule = null;
function loadChart() {
chartModule ??= import('./chart.js');
return chartModule;
}
button.addEventListener('pointerenter', loadChart, { once: true });
button.addEventListener('focus', loadChart, { once: true });
button.addEventListener('click', async () => {
button.disabled = true;
const { renderChart } = await loadChart();
renderChart(document.querySelector('#chart'));
button.disabled = false;
});Storing the promise rather than the result means that concurrent callers share one request. The runtime would deduplicate the fetch anyway. The stored promise also gives you one place to add a spinner or a retry later.
Conditional Loading
Sometimes you can tell at runtime whether a module is needed at all. Typical cases are feature detection, user settings, and the current environment.
async function ensureIntlSegmenter() {
if (!('Segmenter' in Intl)) {
await import('./polyfills/intl-segmenter.js');
}
}
async function loadEditor(user) {
const path = user.prefersMarkdown
? './editors/markdown.js'
: './editors/rich-text.js';
const { createEditor } = await import(path);
return createEditor(document.querySelector('#editor'));
}Browsers that already support Intl.Segmenter never download the polyfill. Each user downloads only one of the two editors.
Common Mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Lazy-loading a module that is also statically imported elsewhere | It already loads at startup, so nothing is saved | Remove the static import, or accept eager loading |
| Lazy-loading tiny modules | An extra network round trip for almost no savings | Lazy-load only large or rarely used code |
| No loading feedback | The UI seems frozen on slow networks | Disable controls or show a spinner |
| Expecting the module to re-run on each `import()` | Side effects happen only once | Export a function and call it each time |
Exercise
A settings panel calls await import('./settings-panel.js') every time it is opened, and settings-panel.js runs console.log('init') at its top level. The user opens the panel three times. How many times is "init" logged, and why?
Show answer
Once. The first import() evaluates the module and caches its instance. The second and third calls resolve to the same cached namespace without evaluating the module again.
Exercise
Your app statically imports ./chart.js in dashboard.js, and you also add await import('./chart.js') behind a button. Does the button make startup faster? Explain.
Show answer
No. The static import in dashboard.js already puts chart.js in the startup graph, so it is fetched and evaluated before the app runs. The dynamic import only gets the cached instance. To defer the module, remove every static import of it.