Menu

How to lazy load Client Components and libraries

Next.js 中的懒加载通过减少渲染路由所需的 JavaScript 数量来提高应用程序的初始加载性能。

它允许你延迟加载客户端组件和导入的库,只在需要时将它们包含在客户端包中。例如,你可能希望延迟加载模态框,直到用户点击打开它。

在 Next.js 中实现懒加载有两种方式:

  1. 使用 next/dynamic 进行动态导入
  2. 使用 React.lazy()Suspense

默认情况下,服务器组件会自动进行代码分割,你可以使用流式传输将 UI 片段从服务器逐步发送到客户端。懒加载适用于客户端组件。

next/dynamic

next/dynamicReact.lazy()Suspense 的组合。它在 apppages 目录中的行为相同,以便于渐进式迁移。

示例

导入客户端组件

app/page.js
'use client'
 
import { useState } from 'react'
import dynamic from 'next/dynamic'
 
// Client Components:
const ComponentA = dynamic(() => import('../components/A'))
const ComponentB = dynamic(() => import('../components/B'))
const ComponentC = dynamic(() => import('../components/C'), { ssr: false })
 
export default function ClientComponentExample() {
  const [showMore, setShowMore] = useState(false)
 
  return (
    <div>
      {/* Load immediately, but in a separate client bundle */}
      <ComponentA />
 
      {/* Load on demand, only when/if the condition is met */}
      {showMore && <ComponentB />}
      <button onClick={() => setShowMore(!showMore)}>Toggle</button>
 
      {/* Load only on the client side */}
      <ComponentC />
    </div>
  )
}

注意: 当服务器组件动态导入客户端组件时,目前支持自动代码分割

跳过 SSR

使用 React.lazy() 和 Suspense 时,客户端组件默认会被预渲染(SSR)。

注意: ssr: false 选项只适用于客户端组件,将其移至客户端组件以确保客户端代码分割正常工作。

如果你想禁用客户端组件的预渲染,可以使用设置为 falsessr 选项:

const ComponentC = dynamic(() => import('../components/C'), { ssr: false })

导入服务器组件

如果你动态导入服务器组件,只有服务器组件的子客户端组件会被懒加载——而不是服务器组件本身。 当你在服务器组件中使用它时,它还有助于预加载静态资源,如 CSS。

app/page.js
import dynamic from 'next/dynamic'
 
// Server Component:
const ServerComponent = dynamic(() => import('../components/ServerComponent'))
 
export default function ServerComponentExample() {
  return (
    <div>
      <ServerComponent />
    </div>
  )
}

注意: 服务器组件不支持 ssr: false 选项。如果你尝试在服务器组件中使用它,将会看到错误。 服务器组件中不允许使用带有 next/dynamicssr: false。请将其移至客户端组件中。

加载外部库

外部库可以使用 import() 函数按需加载。这个例子使用外部库 fuse.js 进行模糊搜索。该模块仅在用户在搜索输入框中输入内容后在客户端加载。

app/page.js
'use client'
 
import { useState } from 'react'
 
const names = ['Tim', 'Joe', 'Bel', 'Lee']
 
export default function Page() {
  const [results, setResults] = useState()
 
  return (
    <div>
      <input
        type="text"
        placeholder="Search"
        onChange={async (e) => {
          const { value } = e.currentTarget
          // Dynamically load fuse.js
          const Fuse = (await import('fuse.js')).default
          const fuse = new Fuse(names)
 
          setResults(fuse.search(value))
        }}
      />
      <pre>Results: {JSON.stringify(results, null, 2)}</pre>
    </div>
  )
}

添加自定义加载组件

app/page.js
'use client'
 
import dynamic from 'next/dynamic'
 
const WithCustomLoading = dynamic(
  () => import('../components/WithCustomLoading'),
  {
    loading: () => <p>Loading...</p>,
  }
)
 
export default function Page() {
  return (
    <div>
      {/* The loading component will be rendered while  <WithCustomLoading/> is loading */}
      <WithCustomLoading />
    </div>
  )
}

导入命名导出

要动态导入命名导出,你可以从 import() 函数返回的 Promise 中返回它:

components/hello.js
'use client'
 
export function Hello() {
  return <p>Hello!</p>
}
app/page.js
import dynamic from 'next/dynamic'
 
const ClientComponent = dynamic(() =>
  import('../components/hello').then((mod) => mod.Hello)
)