# Code splitting with dynamic import()

> How dynamic import() splits a PWA's JavaScript into chunks loaded on demand, what route, component, and vendor splits save, and where import() is forbidden.

Code splitting divides a JavaScript bundle so the browser downloads only the code a route needs
at startup, then parses and executes it. Use `import()` to load the rest on demand; this expression
returns a promise that resolves to a module namespace object. In a PWA
the technique shortens the time to the first interaction, and because each chunk is its own file the
service worker can cache and update chunks one by one.

## How it works

A static `import` declaration is hoisted and evaluated before any of the importing module's
code runs, so every static dependency of the entry module is in the startup graph. `import(specifier)` is an
expression: a bundler set up for splitting emits the target module as a separate file, the browser fetches it when
the expression runs, and the promise fulfils with the module's exports (`javascript.operators.import`:
Chrome 63, Firefox 67, Safari 11.1). A module that has loaded and linked is evaluated once and
cached by its resolved URL, so repeated `import()` calls return the same namespace without a
request; only evaluation failures are cached as failures, while a failed load or link may be retried on a
later call, subject to HTTP caching ([import()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import),
developer.mozilla.org).

### Where to split

- Split by route so each route's view is its own chunk, loaded when the router matches it. This
  is the usual first split in app-like PWAs, and framework routers offer it through lazy
  components.
- Load heavy components on first use. Editors and charts are examples, as are maps. Render a
  lightweight placeholder immediately while the component loads.
- Put third-party dependencies into a chunk of their own. They change less
  often than application code, so a deploy that touches only the app leaves the vendor chunk's
  cache entry valid.

The trade-off is latency at the moment of use. A chunk requested on click usually arrives after a
network round trip unless the service worker precached it, the HTTP cache holds it, or the page issued
`<link rel="modulepreload">` for it. Fetching likely chunks early, once startup work is done,
can hide that delay without growing startup.

### Where import() is unavailable

`import()` works in windows, dedicated workers, and shared workers, and rejects with a `TypeError` in a
service worker and in worklets ([HTML Standard](https://html.spec.whatwg.org/multipage/webappapis.html)). A service worker that needs optional code can bundle it or
load it with `importScripts()`, which is synchronous and, per the service worker spec, only
fetches new scripts while the worker is parsed or installing (initial evaluation and the install event).

### Support position

Dynamic `import()` has been in every engine since Chrome 63, Firefox 67, Safari 11.1, and
Edge 79 (BCD `javascript.operators.import`), and bundlers such as webpack, Rollup, and Parcel treat it as a split point. esbuild does so only with its `splitting` option on and ESM output. The gaps are service workers
and worklets, where the HTML Standard rejects it.

## Examples

Routes and optional components can load on demand with `import()`.

### Loading a route's module when it is first matched

The router maps a path to a dynamic import. The chunk is fetched on first navigation to the
route and comes from the module cache afterwards.

```js
const routes = {
  '/': () => import('./views/home.js'),
  '/settings': () => import('./views/settings.js'),
  '/editor': () => import('./views/editor.js'),
};

async function navigate(path) {
  const load = routes[path] ?? routes['/'];
  const view = await load();
  view.render(document.querySelector('#app'));
}
```

Calling the loader for the next likely route ahead of time (for example `routes['/editor']()` when the
user hovers the Edit button) fetches and evaluates that chunk before the click, so the round trip is
hidden and the chunk stays out of startup.

### Loading a heavy component on interaction

The chart library loads only if the user clicks the button,
and the catch keeps an offline failure from breaking the page.

```js
button.addEventListener('click', async () => {
  button.disabled = true;
  try {
    const { renderChart } = await import('./chart.js');
    renderChart(document.querySelector('#chart'), data);
  } catch (err) {
    showMessage('The chart could not be loaded. Check your connection and try again.');
    button.disabled = false;
  }
});
```

A second click after a failed load may fetch the chunk again, since a failed load is not kept as an
evaluation failure; the HTTP cache still applies.

### Detecting dynamic import and keeping a bundled fallback

Engines without `import()` are older than those in the support section, but a build that must
serve them can ship a single bundle to them. The code wraps every `import()` in `new Function()` so
that parsers without the syntax do not reject the whole script (which needs a CSP that allows `unsafe-eval`).

```js
function supportsDynamicImport() {
  if (!('noModule' in HTMLScriptElement.prototype)) {
    return false; // no module scripts at all: no import() either
  }
  try {
    new Function('return import("data:text/javascript,")');
    return true;
  } catch {
    return false; // modules but no import(): load the single legacy bundle instead
  }
}

if (supportsDynamicImport()) {
  new Function('return import("/app.modern.js")')();
} else {
  const script = document.createElement('script');
  script.src = '/app.legacy.js';
  document.head.append(script);
}
```

The `noModule` check rules out engines older than module scripts before the parser probe. The
probe constructs the function without calling it, so it issues no request.

:::note
Chrome DevTools has a Coverage panel, opened from the Command Menu with **Show Coverage**. For each
resource it lists **Total Bytes**, **Unused Bytes**, and a **Usage Visualization** bar, where the gray
part of the bar is unused bytes and the green part is used bytes ([Coverage: find unused JavaScript and
CSS](https://developer.chrome.com/docs/devtools/coverage), developer.chrome.com). Comparing
**Unused Bytes** for the main bundle before and after splitting a route gives a rough idea of how much
startup code the split removed. The [Network panel reference](https://developer.chrome.com/docs/devtools/network/reference) describes a Waterfall column that breaks down each request's activity, which includes the request for a split chunk.
:::

## See also

- [import()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import) (developer.mozilla.org)
- [Reduce JavaScript payloads with code splitting](https://web.dev/articles/reduce-javascript-payloads-with-code-splitting) (web.dev)
- [Coverage: find unused JavaScript and CSS](https://developer.chrome.com/docs/devtools/coverage) (developer.chrome.com)
- [Core Web Vitals (LCP, INP, and CLS)](/reference/performance/core-web-vitals/)
- [Precaching strategies](/reference/performance/precaching/)
- [Resource hints (preload and preconnect)](/reference/performance/resource-hints/)