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>
  )
}

效果如下

相关推荐
ZPC82104 小时前
如何创建一个单例类 (Singleton)
开发语言·前端·人工智能
紫_龙5 小时前
最新版vue3+TypeScript开发入门到实战教程之重要详解readonly/shallowReadOnly
前端·javascript·typescript
roamingcode6 小时前
前端 AI Agent 多智能体协作架构:从对抗式排查到工作流解耦
前端·人工智能·架构·agent·team
蓝莓味的口香糖7 小时前
【vue】初始化 Vue 项目
前端·javascript·vue.js
光影少年8 小时前
数组去重方法
开发语言·前端·javascript
我命由我123458 小时前
浏览器的 JS 模块化支持观察记录
开发语言·前端·javascript·css·html·ecmascript·html5
weixin_443478518 小时前
Flutter第三方常用组件包之路由管理
前端·javascript·flutter
武藤一雄8 小时前
C# 异步回调与等待机制
前端·microsoft·设计模式·微软·c#·.netcore
啥都不懂的小小白9 小时前
前端CSS入门详解
前端·css
林恒smileZAZ9 小时前
前端大屏适配方案:rem、vw/vh、scale 到底选哪个?
开发语言·前端·css·css3