← Back to JavaScript, page 10

javascript-0191 · Medium mid

How does dynamic import() work, and how do you use it for code splitting and preloading?

import(specifier) loads a module on demand and returns a promise for its namespace object. The module is fetched and evaluated once and cached, so later calls reuse it. Bundlers turn each dynamic import into a separate chunk, which lets you load code for routes or heavy features only when needed. Handle failures, avoid waterfalls, and preload when the user is likely to need the code.

Full answer

Static import statements are resolved before the code runs. import('./chart.js') is an expression that can run at any time, anywhere, in modules and classic scripts, and returns a promise.

Behavior:

  • The promise resolves to the module namespace object: const { render } = await import('./chart.js'), and the default export is in .default.
  • The module is loaded and evaluated once per URL (per module map). Later import() calls return the same namespace without running the module again. Top-level await in the module delays the resolution.
  • The specifier can be computed (import(./locales/${lang}.js)), but bundlers need a pattern they can analyze, and they may bundle every matching file.
  • If loading fails (network, 404, syntax error), the promise rejects. A failed fetch is not retried automatically by the browser for the same specifier in some engines, so deployment mismatches (an old page asking for a deleted hashed chunk) need a handler: show a message or reload the page.

Using it for code splitting:

  1. Split by route: load a page's code when the user navigates. Frameworks wrap this as lazy(() => import('./Page')).
  2. Split by feature: heavy editors, charts, PDF tools, and rarely used dialogs.
  3. Split by condition: polyfills or locale data only when needed.
  4. Bundlers (Webpack, Rollup, Vite, esbuild) create a chunk per dynamic import and shared chunks for common dependencies, and give hashed file names for long-term caching.

Avoiding the costs:

  • Waterfalls: a chunk that imports another chunk after it loads delays the feature. Preload or use <link rel="modulepreload"> for chunks you know you will need.
  • Prefetch on intent: start import() on hover, focus, or when the browser is idle, and keep the promise so the click reuses it.
  • Do not split too small. Many tiny chunks add requests, so measure with the network panel and a bundle analyzer.
  • Show a loading state and handle errors with a retry.

Dynamic import also works in Node.js, including from CommonJS, which is how a CommonJS file can load an ES module.

javascript
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { pathToFileURL } = require('node:url');

const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'dynamic-import-'));
const write = (name, source) => fs.writeFileSync(path.join(dir, name), source);
const load = (name) => import(pathToFileURL(path.join(dir, name)).href);

write('chart.mjs', `
  globalThis.__evaluations = (globalThis.__evaluations ?? 0) + 1;
  export const render = (data) => 'chart of ' + data.join('+');
  export default function describe() { return 'default export'; }
`);
write('slow.mjs', `
  await new Promise((resolve) => setTimeout(resolve, 20));
  export const ready = 'top-level await finished';
`);
write('broken.mjs', 'export const x = ;');
write('en.mjs', 'export default { hello: "Hello" };');
write('hi.mjs', 'export default { hello: "Namaste" };');

const preloaded = new Map();
const prefetch = (name) => preloaded.get(name) ?? (preloaded.set(name, load(name)), preloaded.get(name));

(async () => {
  console.log('before any import, evaluations:', globalThis.__evaluations ?? 0);
  const chart = await load('chart.mjs');
  console.log('namespace keys:', Object.keys(chart), '| render:', chart.render([1, 2]), '| default:', chart.default());
  const again = await load('chart.mjs');
  console.log('same namespace object:', again === chart, '| evaluations:', globalThis.__evaluations);

  console.log('top-level await:', (await load('slow.mjs')).ready);

  try {
    await load('broken.mjs');
  } catch (error) {
    console.log('syntax error rejects the promise:', error.name);
  }
  try {
    await load('missing.mjs');
  } catch (error) {
    console.log('missing file rejects:', error.code);
  }

  const p1 = prefetch('en.mjs');
  const p2 = prefetch('en.mjs');
  console.log('prefetch keeps one promise:', p1 === p2);
  const [en, hi] = await Promise.all([p1, load('hi.mjs')]);
  console.log('parallel loads:', en.default.hello, hi.default.hello);

  const lang = 'hi';
  console.log('computed specifier:', (await load(`${lang}.mjs`)).default.hello);

  const lazy = () => {
    let promise;
    return () => (promise ??= load('chart.mjs'));
  };
  const getChart = lazy();
  console.log('lazy wrapper shares the load:', (await Promise.all([getChart(), getChart()])).every((m) => m === chart));

  fs.rmSync(dir, { recursive: true, force: true });
})();

Run with Node.js v24.22.1 as js-191.js; two runs gave identical output. Output: before any import, evaluations: 0 namespace keys: [ 'default', 'render' ] | render: chart of 1+2 | default: default export same namespace object: true | evaluations: 1 top-level await: top-level await finished syntax error rejects the promise: SyntaxError missing file rejects: ERR_MODULE_NOT_FOUND prefetch keeps one promise: true parallel loads: Hello Namaste computed specifier: Namaste lazy wrapper shares the load: true

Key points

  • import() returns a promise for the namespace object; the default export is in .default.
  • A module is fetched and evaluated once, then cached.
  • Bundlers make a chunk per dynamic import; split by route, feature, and condition.
  • Avoid waterfalls with modulepreload and prefetch on intent; keep the promise.
  • Handle load failures, especially after deployments change hashed file names.

Common mistakes

  • Importing everything statically and shipping one huge bundle.
  • Splitting into many tiny chunks and creating request waterfalls.
  • Not handling a failed chunk load after a new deployment.
  • Using import() with a fully dynamic specifier that a bundler cannot analyze.

Follow-ups

  • How does modulepreload differ from prefetch?
  • How would you retry a failed chunk load?
  • How do you load an ES module from CommonJS?

Tips

  • Say it returns a promise for the namespace and that modules are cached.
  • Give three split points: route, feature, condition.
  • Mention loading states, errors, and prefetch on intent.