延遲載入
延遲載入 在 Next.js 中,透過減少渲染路由所需的 JavaScript 數量,來幫助提升應用程式的初始載入效能。
它允許你延遲載入客戶端元件和導入的函式庫,並且僅在需要時將它們包含在客戶端 bundle 中。例如,你可能想要延遲載入 modal,直到使用者點擊開啟它。
你可以使用兩種方式在 Next.js 中實作延遲載入
- 使用動態導入與
next/dynamic
- 使用
React.lazy()
與 Suspense
預設情況下,伺服器元件會自動程式碼分割,你可以使用串流從伺服器逐步將 UI 片段發送到客戶端。延遲載入適用於客戶端元件。
next/dynamic
next/dynamic
是 React.lazy()
和 Suspense 的組合。它在 app
和 pages
目錄中的行為方式相同,以允許增量遷移。
範例
導入客戶端元件
'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
選項僅適用於客戶端元件,請將其移至客戶端元件中,以確保客戶端程式碼分割正常運作。
如果你想為客戶端元件停用預先渲染,你可以使用 ssr
選項並將其設定為 false
const ComponentC = dynamic(() => import('../components/C'), { ssr: false })
導入伺服器元件
如果你動態導入伺服器元件,則只有作為伺服器元件子元件的客戶端元件會被延遲載入 - 而不是伺服器元件本身。當你在伺服器元件中使用它時,這也有助於預先載入靜態資源,例如 CSS。
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
進行模糊搜尋。該模組僅在使用者在搜尋輸入框中輸入內容後才在客戶端載入。
'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>
)
}
新增自訂載入元件
'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 中傳回它
'use client'
export function Hello() {
return <p>Hello!</p>
}
import dynamic from 'next/dynamic'
const ClientComponent = dynamic(() =>
import('../components/hello').then((mod) => mod.Hello)
)
這有幫助嗎?