延遲載入
在 Next.js 中,延遲載入有助於提升應用程式的初始載入效能,方法是減少渲染路由所需的 JavaScript 數量。
它允許您延遲載入客戶端組件和導入的函式庫,僅在需要時才將它們包含在客戶端套件中。例如,您可能希望延遲載入模態框,直到使用者點擊開啟它。
在 Next.js 中,您可以透過兩種方式實現延遲載入:
- 使用
next/dynamic
的動態導入 - 搭配 Suspense 使用
React.lazy()
預設情況下,伺服器組件會自動進行程式碼分割,您可以使用串流將 UI 片段從伺服器逐步發送到客戶端。延遲載入適用於客戶端組件。
next/dynamic
next/dynamic
是 React.lazy()
和 Suspense 的組合。它在 app
和 pages
目錄中的行為相同,以便進行漸進式遷移。
範例
導入客戶端組件
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
選項僅適用於客戶端組件,請將其移至客戶端組件以確保客戶端程式碼分割正常運作。
如果您想停用客戶端組件的預渲染,可以使用設定為 false
的 ssr
選項。
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/dynamic
不允許使用ssr: 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>
)
}
新增自訂載入組件
導入命名匯出
要動態導入命名匯出,您可以從 import()
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)
)