skip to content

In a Vite production build, what does Vite add around a dynamic `import()`, and when does it fire the `vite:preloadError` event?

level: middleimportance: should knowfreq 8%

answer

  1. dynamic import, rewritten at build time
  2. dependencies fetched in parallel
  3. a polyfill injected per HTML entry
  4. an event on window, not HMR
  5. payload, preventDefault, then reload

basics

~20 s

Vite rewrites each code-split dynamic import() with a preload step that fetches the chunk's imported chunks and CSS in parallel; if loading fails, it dispatches vite:preloadError on window, with the original error in event.payload, and event.preventDefault() stops that error being thrown.

solid answer

~50 s

In a production build Vite wraps every code-split `import()` in a preload step: it knows from the build which chunks and CSS files the target chunk imports, so it requests them together instead of letting the browser discover them one round trip at a time, and the async chunk is evaluated only after its CSS has loaded. Entry chunks and their direct imports also get `<link rel="modulepreload">` tags in the built HTML, and `build.modulePreload` (default `{ polyfill: true }`) injects a module preload polyfill into each `index.html` entry. When a dynamic import fails to load, Vite dispatches `vite:preloadError` on `window`; `event.payload` holds the original import error, and calling `event.preventDefault()` means the error will not be thrown. The usual handler reloads the page, paired with `Cache-Control: no-cache` on the HTML so the reload fetches the new build.

go deeper

for a junior

Know that Vite preloads a lazy chunk's dependencies for you and that a failed chunk load raises vite:preloadError on window.

for a middle

Explain how the preload step removes import round trips, what event.payload and event.preventDefault() do, and where the module preload polyfill gets injected.

for a senior

Diagnose stale-deploy chunk failures: wire a reload handler, set no-cache on the HTML, and handle the polyfill when a backend renders HTML from the manifest.

for a principal

Decide where chunk-load recovery lives across apps, in a shared entry module or the platform shell, and how it interacts with your asset-retention policy.

## The problem the preload step solves A **dynamic import**, `import('./claims-detail.js')`, asks the browser for a chunk only when the code runs. Without help, the browser downloads that chunk, parses it, and only then sees that it statically imports a shared chunk, which it must fetch next: one extra **round trip** per level of imports. Vite's build knows the whole chunk graph in advance, so it removes those round trips. ## What Vite adds at build time 1. **A preload step around each code-split `import()`.** Vite rewrites the call so that, when chunk `A` is requested, every chunk `A` imports (traced to any depth) is fetched at the same time. The docs draw it as `Entry ---> (A + C)` instead of `Entry ---> A ---> C`. 2. **CSS for the async chunk.** With `build.cssCodeSplit: true` (the default), CSS used by an async chunk becomes its own file. The preload step loads it through a `<link>` tag, and the chunk is evaluated only after that CSS has loaded, which avoids a flash of unstyled content. 3. **Preload tags in the HTML.** For entry chunks and their direct imports, Vite writes `<link rel="modulepreload">` tags into the built `index.html`. 4. **A module preload polyfill.** `build.modulePreload` defaults to `{ polyfill: true }`, which injects a polyfill into the proxy module of each `index.html` entry. If your entry is not HTML, for example when a server renders the page from the build manifest, you import it yourself with `import 'vite/modulepreload-polyfill'`, or turn it off with `{ polyfill: false }`. | Setting | Default | What it changes | |---|---|---| | `build.modulePreload.polyfill` | `true` | injects the module preload polyfill into HTML entries | | `build.modulePreload.resolveDependencies` | none (experimental) | a function that filters or rewrites the list of chunks preloaded for each dynamic import | | `build.cssCodeSplit` | `true` | CSS of async chunks is split out and loaded with them | `build.modulePreload` does not apply to **library mode**, so a library build gets no preload polyfill. ## When `vite:preloadError` fires Vite dispatches **`vite:preloadError`** on `window` when it fails to load a dynamic import. The event is typed in Vite's client types as an `Event` with a **`payload`** property holding the original error. - **`event.payload`**: the import error, useful for logging the failing chunk. - **`event.preventDefault()`**: Vite will then not throw the error. - **Listening**: a plain `window.addEventListener('vite:preloadError', handler)` in your entry code. It is not part of the `import.meta.hot` API, which exists only in development. The typical cause in production is a **deploy**. A user who loaded the previous build still runs its code; when it asks for an old chunk that the host has already deleted, the request fails. The Vite docs suggest a handler that calls `window.location.reload()`, and they add a condition: serve the HTML with **`Cache-Control: no-cache`**, otherwise the reload can bring back the old HTML that points at the same old assets. ```js window.addEventListener('vite:preloadError', (event) => { console.warn('chunk failed to load', event.payload) event.preventDefault() window.location.reload() }) ``` How to stop a reload loop, and how long old assets should stay available, are routing and caching decisions; this event is only the hook Vite gives you. ## Checking it in the network panel 1. Build and serve `dist` (for example with `vite preview`), then open a route that triggers a dynamic import. 2. In the network panel, the lazy chunk and the shared chunks it imports should start at about the same time, rather than one after another. 3. Check that the route's split CSS arrives before the chunk runs, so there is no unstyled flash. 4. To see the error path, delete one lazy chunk from `dist` and navigate to its route: the import fails, `vite:preloadError` fires, and your handler's log or reload should follow. ## Common misreadings - **"It is an HMR event."** HMR events are development-only and use `import.meta.hot.on`; `vite:preloadError` is a window event in the built app. - **"`preventDefault()` retries the import."** It only stops the error being thrown; any recovery, such as a reload, is yours to write. - **"The browser still fetches shared chunks one level at a time."** In a Vite build the preload step has already listed them, so they are requested together. - **"Library builds get the polyfill too."** `build.modulePreload` does not apply to library mode.

  • Your backend renders the HTML itself from the build manifest instead of serving Vite's `index.html`. What must the entry do about module preloading?
    Vite injects its module preload polyfill only into the proxy module of an `index.html` entry. With a non-HTML entry, and the polyfill left enabled, add `import 'vite/modulepreload-polyfill'` at the top of the entry, or set `build.modulePreload: { polyfill: false }` if every browser you support has native module preload. The backend can then add `<link rel="modulepreload">` tags from each entry's `imports` in the manifest.
  • Why do the Vite docs tie a reloading `vite:preloadError` handler to `Cache-Control: no-cache` on the HTML?
    The reload is only useful if it fetches the new build's HTML, which references the new chunk names. If the HTML can be served from cache, the reload brings back the old document, the old entry asks for the same deleted chunks, and the import fails again. `no-cache` makes the browser revalidate the HTML on every load.

  • vite:preloadError is an HMR event you listen to with import.meta.hot.on
  • Calling event.preventDefault() makes Vite retry the failed import
  • In a Vite build the browser fetches a lazy chunk's shared chunks only after parsing it
  • Library-mode builds also get Vite's module preload polyfill
  • A custom non-HTML entry gets the preload polyfill injected automatically