Skip to content
Tutorials Center
My learning

Topics

Lesson 37 of 38 ยท Projects and Practice

Project: A Lazy-Loaded Dashboard

Project: design a dashboard whose routes and widgets load on demand with webpack dynamic imports, hover prefetch, loading and error states, retries and a size budget per route.

A dashboard is the classic place where code splitting pays off. Users land on one screen, but the bundle contains charts, tables, a settings editor and an admin area. In this project you will plan and build the loading strategy for such an app: route-level chunks, widget-level chunks, hover prefetching, loading and error states, and a size budget for each route. You will write the real webpack-facing code as read-only listings, and run the logic in Node.js stand-ins.

Webpack is not runnable on this site. The source listings are read-only and meant to be copied into your own project. The TryIt blocks are Node.js stand-ins for the router, chunk loader and failure handling; "chunks" are fake modules with simulated delays.

Requirements

  1. Home (/) shows a summary and must be fast: no chart library in the first load.
  2. Reports (/reports) draws a chart with a heavy library.
  3. Settings (/settings) has a form editor; Admin (/admin) is for staff only.
  4. Moving the mouse over a nav link should prefetch that route's chunk.
  5. A failed chunk load shows an error with a retry button, not a blank page.
  6. Each route has a size budget; the build fails if it is exceeded.

Step 1: the route table

The route table is the single place where lazy loading is decided. Each entry holds a function that calls import(); nothing is downloaded until it runs.

JavaScript
// src/routes.js (read-only listing)
export const routes = {
  '/':         { title: 'Overview', load: () => import(/* webpackChunkName: "overview" */ './pages/overview.js') },
  '/reports':  { title: 'Reports',  load: () => import(/* webpackChunkName: "reports"  */ './pages/reports.js') },
  '/settings': { title: 'Settings', load: () => import(/* webpackChunkName: "settings" */ './pages/settings.js') },
  '/admin':    { title: 'Admin',    load: () => import(/* webpackChunkName: "admin"    */ './pages/admin.js') },
};

With webpackChunkName, the output has files named overview.[hash].chunk.js, reports... and so on, which makes the bundle analysis easy to read. Heavy dependencies (the chart library) are imported inside reports.js, so they travel with that chunk only, and splitChunks extracts any code shared by several routes.

Step 2: a router with loading and caching

The router asks the route for its module, shows "Loading..." while the promise is pending, and renders the result. This stand-in uses simulated delays so you can watch the sequence, including that a second visit is instant.

Node.js Stand-in: lazy router with a loading state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Showing the spinner only after a short delay avoids flashes of "Loading..." for fast loads. In React you would do this with Suspense and React.lazy (see Webpack with React); in Vue, defineAsyncComponent has delay and timeout options.

Step 3: prefetch on hover and idle

Waiting for a click to start the download wastes time. Two cheap improvements:

JavaScript
// src/nav.js (read-only listing)
import { routes } from './routes.js';

document.querySelectorAll('[data-route]').forEach((link) => {
  const warm = () => routes[link.dataset.route].load();   // starts the download, result is cached
  link.addEventListener('pointerenter', warm, { once: true });
  link.addEventListener('focus', warm, { once: true });
});

// While the browser is idle, warm the most likely next route.
window.requestIdleCallback?.(() => routes['/reports'].load());

Alternatively use /* webpackPrefetch: true */ in the import, which makes webpack insert a <link rel="prefetch">. Hover prefetching is more precise (it follows what the user is about to do) and the idle approach is simpler. Use them carefully: on a metered connection you should not download everything. Check navigator.connection?.saveData and skip prefetching if it is true.

Step 4: failures and retries

Chunk requests fail when the user goes offline, or after a new deploy removes old files. The router should retry and then show an error with a button.

Node.js Stand-in: retry, then show an error state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

For a stale-chunk error after a deploy, the most reliable fix is to keep old assets available for some time and offer a reload. A small service worker that notifies the page when a new version exists is a common addition.

Step 5: a budget per route

Finally, protect the result. Use the built-in performance hints for the total, and in CI check route chunks against your own list. The stand-in below shows the idea of a per-route budget check, using sizes you would read from stats.json.

Node.js Stand-in: budget per route

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

If reports goes over budget, the usual cure is more splitting: load the chart library only when the chart scrolls into view, or replace the library with a lighter one.

Extension ideas

  • Lazy-load widgets inside a page with IntersectionObserver so charts below the fold load only when visible.
  • Move the admin area to a separate entry or federated remote so non-staff never download it.
  • Add real measurements with the performance API and report them to your analytics.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Where should the decision to lazy-load a route live?

    A route table with import() functions keeps splitting decisions in one place and nothing downloads until a route is used.
  2. 2. Why show a loading spinner only after a short delay?

    Fast loads finish before the delay, so users see no flicker; slow loads still get feedback.
  3. 3. Which situation causes a ChunkLoadError after a deploy?

    Hashed chunk names change per release. An open tab may still ask for the previous names.
  4. 4. What is a good guard for prefetching?

    Respecting data-saver mode avoids wasting a user's bandwidth on speculative downloads.

Summary

  • Put every lazy decision in a route table of import() functions with named chunks.
  • Cache chunk promises, show delayed loading states and handle failures with retries and a clear message.
  • Prefetch on hover, focus or idle, but respect data-saver settings.
  • Set a per-route budget and check it in CI.

Next: Troubleshooting and Practice