Nextjs的懒加载使用方法

在项目中,适当地对一些比较重的模块进行懒加载处理,能提高应用的初始化加载速度, nextjs提供了nextjs/dynamic这个模块来实现懒加载。

基础例子

jsx 复制代码
'use client'

import { useCallback, useState } from 'react'
import dynamic from 'next/dynamic'
const ComponentA = dynamic(() => import('./components/A'))
const ComponentB = dynamic(() => import('./components/B'))
const ComponentC = dynamic(() => import('./components/C'), { ssr: false })

const WithCustomLoading = dynamic(
  () => import('./components/B'),
  {
    loading: () => <p>Loading...</p>,
  }
)

export default function Home() {
  const [visible, setVisible] = useState(false)
  const handleTrigger = useCallback(() => { setVisible(!visible) })
  return (
    <main>

      {/* 模块 A 会被分包,并且立即加载 */}
      <ComponentA />
      {/* 模块 B 会按需加载 */}
      {visible && <ComponentB />}
      {/* 模块 C 会被分包,并且关闭ssr 模式,在客户端执行 */}
      <ComponentC />

      <button onClick={handleTrigger}>trigger</button>
    </main>
  )
}

加载情况可以看下面的截图,模块 A 和模块 C 都被分包

当点击了按钮,将visible的值改为 true 时,模块 B 也被动态加载。

懒加载外部库

可以用到import()来引入模块

module.a.js

js 复制代码
export const name = 1
export const isModule = true
js 复制代码
// 通过相对路径来引入模块
import("./module.a").then(({ name, isModule }) => {
  console.log(name, isModule)
})
// 引入外部库
import("fuse.js").then((module) => {
  const Fuse = module.default
  console.log(Fuse)
})

懒加载组件时的加载回显

js 复制代码
import dynamic from 'next/dynamic'

const WithCustomLoading = dynamic(
  () => import('../components/WithCustomLoading'),
  {
    loading: () => <p>Loading...</p>,
  }
)

export default function Page() {
  return (
    <div>
      {/* 当组件加载时会展示 loading 状态  <WithCustomLoading/> */}
      <WithCustomLoading />
    </div>
  )
}

效果如下

相关推荐
花归去29 分钟前
ant的a-table更改表格的高度
前端·javascript·html
sibylyue1 小时前
基于 Vben Admin 框架的 Vue 3 前端项目配置文件及常用命令
前端·javascript·vue.js
知几蜗牛1 小时前
0 后端 · 0 数据库 · 0 备案:用 AI 两天搓出的股票管理系统,开源了
前端·后端·llm
雪芽蓝域zzs1 小时前
Element‑Plus icon 图标名称查询 & 和菜单 meta.icon 字段映射
前端
01_ice2 小时前
前端学习css
前端·css·学习
愚公搬代码2 小时前
【愚公系列】《Web应用安全》010-Repeater模块的使用
前端·安全
Cache技术分享3 小时前
503. Java 反射 - 编写 ServiceFactory 类
前端·后端
赵大仁3 小时前
AI 限流 UX 设计:排队、降级、告知与用户预期管理
前端·ai·限流·用户体验·产品设计
__sjfzllv___3 小时前
在职前端Leader学习/转行 AI Agent -DAY37
前端
用户2181697049303 小时前
Flutter (二十二) GlobalKey
前端