Skip to content

Lazy 加载

一句话解释

Lazy 加载平均值 deferring 加载的 组件直到它 是 actually rendered, reducing 初始 bundle 大小.

用大白话说

Lazy loading (code splitting) means a component's code is not included in the main bundle — it is fetched on demand when the component is first rendered. This reduces the initial JavaScript payload and speeds up the first paint.

React provides React.lazy() for lazy-loading components and <Suspense> for showing a fallback while the code loads. const Admin = React.lazy(() => import('./Admin')) creates a component that is loaded on first render. Wrap it in <Suspense fallback={<Spinner />}>... to show a loading indicator.

Lazy loading is most useful for route-level components (pages the user may never visit), large modals, or heavy features. The trade-off is a slight delay when the component is first needed, but the initial load is much faster.

示例

jsx
const AdminPanel = React.lazy(() => import("./AdminPanel"));

function App() {
  return (
    <Suspense fallback={<div>Loading...</div>}>
      <AdminPanel />
    </Suspense>
  );
}

AdminPanel's code 是 in separate 块. 当它 首先渲染, React shows fallback 虽然块 加载, 然后渲染组件.

相关术语

相关资源

相关课程

  • Lazy 加载

    学习 React.lazy and Suspense for code 拆分.

解读错误信息

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

查看错误

← 返回术语表