Skip to content

Lazy 加载 and Code 拆分

Reducing bundle 大小使用 React.lazy, Suspense, and 动态导入.

你将学到

  • 什么 code 拆分是 and 为什么它 matters
  • Using React.lazy 到 lazily 加载组件
  • Wrapping lazy 组件 in Suspense 使用 fallbacks
  • Route-based code 拆分策略

概念讲解

Why Code Splitting?

By default, all your JavaScript is bundled into a single file. As your app grows, this bundle becomes large, slowing the initial page load — the browser must download and parse the entire bundle before anything renders. Code splitting breaks the bundle into smaller chunks that are loaded on demand. This dramatically improves initial load time because the user only downloads the code for the page they are viewing, not the entire application.

React.lazy

React.lazy lets you render a dynamic import as a regular component. You pass it a function that returns import(): const Settings = React.lazy(() => import("./Settings")). The component is loaded only when it is first rendered. The dynamic import() returns a promise that resolves to the module, and React.lazy handles the suspense of waiting for it. This is the simplest way to code-split at the component level.

Suspense

React.lazy components must be wrapped in a <Suspense> boundary, which shows a fallback (like a loading spinner) while the lazy component is loading. You can have multiple Suspense boundaries at different levels — each shows its own fallback independently. Suspense can also be used with data fetching (in experimental concurrent features) and with React Router's lazy route loading. The fallback can be anything: a spinner, a skeleton, or a placeholder layout.

Route-Based Splitting

The most impactful code splitting is route-based: each route's components are in a separate chunk. When the user navigates to a new page, only that page's code is loaded. This is natural with React Router — wrap each route element in a Suspense boundary and use React.lazy for the page components. The initial load only includes the code for the landing page, and other pages load on demand as the user navigates.

Analyzing Bundle Size

Use tools like vite-bundle-visualizer or webpack-bundle-analyzer to see what is in your bundle and identify large dependencies that could be split or replaced. Look for large libraries that are only used on one page — these are prime candidates for lazy loading. Also check for duplicate dependencies and tree-shaking issues where libraries prevent dead code elimination.

示例代码

              import React, { Suspense, lazy } from "react";
import { BrowserRouter, Routes, Route } from "react-router-dom";

// Lazy-load page components — each becomes a separate bundle chunk.
const Home = lazy(() => import("./pages/Home"));
const Dashboard = lazy(() => import("./pages/Dashboard"));
const Settings = lazy(() => import("./pages/Settings"));

function LoadingFallback() {
  return (
    <div className="loading-screen">
      <div className="spinner" />
      <p>Loading page...</p>
    </div>
  );
}

function App() {
  return (
    <BrowserRouter>
      {/* Suspense shows fallback while any lazy route is loading */}
      <Suspense fallback={<LoadingFallback />}>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/dashboard" element={<Dashboard />} />
          <Route path="/settings" element={<Settings />} />
        </Routes>
      </Suspense>
    </BrowserRouter>
  );
}
            

每个 page 是 lazy-加载到 它的 own bundle 块. Suspense shows 加载 screen 虽然块 downloads. 初始加载仅 包含 Home page code.

动手试一试

  • Code Minifier

    See 如何 code 拆分 reduces 大小的 individual bundle 块.

  • Code Diff

    Compare bundle 结构之前 and 之后添加 lazy 加载.

常见错误

错误写法

Using React.lazy 不使用 Suspense 边界

正确做法

每个 React.lazy 组件必须是 内部 Suspense 边界. 不使用它, React 有否 fallback 到 show 虽然加载 and 将 throw 错误. Wrap at route level or 组件 level.

错误写法

Lazy-加载组件那个是 需要 on 初始 page

正确做法

仅 lazy-加载组件那个是 不需要 immediately (other routes, modals, heavy widgets). Lazy-加载初始 page's 组件添加加载 flash 使用否 benefit.

练习 Lazy 加载 and Code 拆分

4 个练习

练习 Lazy 加载 and Code 拆分

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误