Vite

Splitting and prefetching Vite routes with import()

Use dynamic imports to keep secondary pages out of Vite's initial download, inspect generated modulepreload links, and prefetch on user intent.

Splitting and prefetching Vite routes with import()

Importing every page from the router puts secondary screens on the initial loading path. I use dynamic imports to split Vite routes and start loading a selected page earlier when a link shows credible navigation intent.

See what the initial route imports

1
2
3
4
5
6
7
8
9
10
11
12
13
// src/router/index.tsx (eager imports)
import { createBrowserRouter } from 'react-router-dom';
import HomeView from '../pages/HomeView';
import ProductDetail from '../pages/ProductDetail';
import CheckoutView from '../pages/CheckoutView';
import UserProfile from '../pages/UserProfile';

export const router = createBrowserRouter([
  { path: '/', element: <HomeView /> },
  { path: '/products/:id', element: <ProductDetail /> },
  { path: '/checkout', element: <CheckoutView /> },
  { path: '/profile', element: <UserProfile /> },
]);

An eager router imports CheckoutView even when the visitor only opens the home page. Any payment SDK and image editing modules reachable through those imports may join the initial dependency graph. The exact chunk layout depends on the bundler, but the browser still needs the modules the entry imports eagerly.

With import(), the runtime can load the route when it is needed. I use this first for heavy routes that many visitors never open. A small component needed for the initial route can usually stay an eager import to avoid an extra asynchronous boundary.

flowchart TD
    subgraph InitialLoad["1. Initial home route"]
        HTML["index.html"] --> CoreJS["index.js + vendor-framework.js"]
        HTML --> Preload["<link rel='modulepreload' href='HomeView.js'>"]
        CoreJS --> Home["HomeView.js (renders first)"]
    end
    subgraph UserAction["2. Navigation or interaction"]
        Hover["Link hover or viewport entry"] --> Prefetch["import('./ProductDetail.js') starts prefetch"]
        Prefetch --> BrowserCache["Module becomes available for later use"]
        Click["Navigate to the route"] --> FastRender["Reuse the already loaded module"]
    end

Load the page with React lazy and Suspense

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
// src/router/index.tsx
import React, { Suspense, lazy } from 'react';
import { createBrowserRouter } from 'react-router-dom';

// Declare page components with dynamic imports
const HomeView = lazy(() => import('../pages/HomeView'));
const ProductDetail = lazy(() => import('../pages/ProductDetail'));
const CheckoutView = lazy(() => import('../pages/CheckoutView'));
const UserProfile = lazy(() => import('../pages/UserProfile'));

// Loading placeholder during navigation
const fallbackStyle: React.CSSProperties = {
  display: 'flex',
  justifyContent: 'center',
  padding: '40px'
};

const RouteFallback: React.FC = () => (
  <div style={fallbackStyle}>
    <div className="skeleton-loader">Loading page...</div>
  </div>
);

export const router = createBrowserRouter([
  {
    path: '/',
    element: (
      <Suspense fallback={<RouteFallback />}>
        <HomeView />
      </Suspense>
    ),
  },
  {
    path: '/products/:id',
    element: (
      <Suspense fallback={<RouteFallback />}>
        <ProductDetail />
      </Suspense>
    ),
  },
  {
    path: '/checkout',
    element: (
      <Suspense fallback={<RouteFallback />}>
        <CheckoutView />
      </Suspense>
    ),
  },
  {
    path: '/profile',
    element: (
      <Suspense fallback={<RouteFallback />}>
        <UserProfile />
      </Suspense>
    ),
  },
]);

React.lazy() starts loading the page module when React tries to render it. Suspense supplies a placeholder while the import is pending. Keep that placeholder close to the content that needs it so the navigation bar and page frame can remain stable. A failed load needs an error boundary or recovery behavior of its own.

The import path must give Vite enough information to resolve a chunk. For an application that generates route entries from files, an explicit map or Vite’s glob imports are easier to inspect and validate than constructing arbitrary paths at runtime.

Inspect Vite’s generated modulepreload hints

Without preloading, a dynamic chunk can download before the browser discovers it also needs a shared chunk. Vite generates preload directives for the entry and can rewrite dynamic imports to request their discovered dependencies in parallel. A generated build may also include a modulepreload polyfill according to configuration.

1
2
3
4
5
6
7
<!-- dist/index.html (generated by Vite) -->
<head>
  <link rel="modulepreload" crossorigin href="/assets/index-B8d3.js">
  <link rel="modulepreload" crossorigin href="/assets/vendor-framework-C1.js">
  <link rel="modulepreload" crossorigin href="/assets/HomeView-D1a8.js">
  <script type="module" crossorigin src="/assets/index-B8d3.js"></script>
</head>

modulepreload gives the browser a hint about which modules to fetch early. HTTP/2 or HTTP/3 can help requests share a connection, but the hint has value even without either transport. It addresses when the browser learns what it needs. Vite preload generation

Prefetch on a short list of meaningful signals

The helper executes the same module factory that the lazy component uses. That starts fetching and can evaluate the module. I deduplicate requests and remove a failed attempt so a later navigation can retry.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
// src/utils/prefetch.ts
type ComponentFactory = () => Promise<unknown>;

const prefetchedMap = new Set<ComponentFactory>();

/**
 * Run the component factory early to load its module.
 */
export function prefetchComponent(factory: ComponentFactory): void {
  if (prefetchedMap.has(factory)) {
    return;
  }
  prefetchedMap.add(factory);
  factory().catch((err) => {
    console.warn('[Prefetch] Module prefetch failed:', err);
    prefetchedMap.delete(factory); // Allow a retry after a failed prefetch
  });
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// src/components/PrefetchLink.tsx
import React from 'react';
import { Link, LinkProps } from 'react-router-dom';
import { prefetchComponent } from '../utils/prefetch';

interface PrefetchLinkProps extends LinkProps {
  prefetchFactory?: () => Promise<unknown>;
}

export const PrefetchLink: React.FC<PrefetchLinkProps> = ({
  to,
  prefetchFactory,
  children,
  onMouseEnter,
  onFocus,
  ...rest
}) => {
  const triggerPrefetch = () => {
    if (prefetchFactory) {
      prefetchComponent(prefetchFactory);
    }
  };

  return (
    <Link
      to={to}
      onMouseEnter={(e) => {
        triggerPrefetch();
        onMouseEnter?.(e);
      }}
      onFocus={(e) => {
        triggerPrefetch();
        onFocus?.(e);
      }}
      {...rest}
    >
      {children}
    </Link>
  );
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// src/components/NavBar.tsx
import React from 'react';
import { PrefetchLink } from './PrefetchLink';

export const NavBar: React.FC = () => {
  return (
    <nav className="navbar">
      <PrefetchLink to="/">Home</PrefetchLink>
      <PrefetchLink
        to="/checkout"
        prefetchFactory={() => import('../pages/CheckoutView')}
      >
        Checkout
      </PrefetchLink>
      <PrefetchLink
        to="/profile"
        prefetchFactory={() => import('../pages/UserProfile')}
      >
        My profile
      </PrefetchLink>
    </nav>
  );
};

Hover and keyboard focus give the page an early signal. Frequently visited routes can also use viewport entry if the network budget allows it, but triggering every link as it scrolls into view can recreate the initial download problem. A pointer hover might provide 100–300 ms before a click. That is enough for some cached or small chunks and only a head start for others.

Verify chunk output and the network request order

Terminal showing separate Vite production chunks for home, product, checkout, and profile Figure 1. The production build emits separate files for each route.

Route chunkSizeGzip
HomeView-D1a8.js34.12 kB10.45 kB
ProductDetail-E4b2.js62.40 kB18.20 kB
CheckoutView-A9c1.js88.15 kB25.80 kB
UserProfile-F2e7.js41.20 kB12.10 kB

These figures describe the route chunks. The home entry in a browser can need other shared modules and CSS as well. I first record a visit without touching any secondary link, then trigger a prefetch and navigate. The request waterfall should show when the route started loading and whether navigation needed another fetch.

Terminal checking generated modulepreload links and static asset caching headers Figure 2. Verify modulepreload in the document and caching on the server that serves the hashed assets.

Production cache headers belong to the deployment serving the files. Verify any one-year immutable policy there with curl -I. During analysis, a bundle report can identify dependencies that are still on the initial route after the split.

This post is licensed under CC BY 4.0 by the author.