NextJS 性能检查表
使用 NextJS 构建 React 应用程序是快速将产品交付给客户的绝佳方式。但您可能会发现,由于网站速度太慢,客户可能不会使用您的网站。以下列出了一些可以提升 NextJS 应用程序性能的方法。
我已将其调整为针对 NextJS 的一些具体内容,但此列表也可以更广泛地应用。
应用
- 前端尽可能完全缓存在 CDN 上(“Jamstacked” https://jamstack.org/)
- 如果无法做到这一点,则在构建时或在服务器上使用增量静态再生(https://www.smashingmagazine.com/2021/04/incremental-static-regeneration-nextjs/)构建页面
- 在指向内部路由的链接中使用模块替换策略(https://nextjs.org/docs/api-reference/next/link)
图片
- 图像可以在构建时获取,也可以在 CDN 请求时获取
- 以正确的尺寸和最高效的格式获取图像(https://ericportis.com/posts/2014/srcset-sizes/)
- 高优先级图像(页面打开时在视口中的图像)使用响应式
preload
(https://www.bronco.co.uk/our-ideas/using-relpreload-for-responsive-images/) - 低优先级图像使用loading="lazy"异步下载
- 尽可能使用应用程序图像组件(https://nextjs.org/docs/api-reference/next/image)
样式
- 不要使用 css-in-js(https://pustelto.com/blog/css-vs-css-in-js-perf/)
- 仅使用过的样式会发送给客户端(https://markmurray.co/blog/tree-shaking-css-modules/)
- 如果使用 css-in-js,请尝试使 css 尽可能静态(https://itnext.io/how-to-increase-css-in-js-performance-by-175x-f30ddeac6bce)
- CSS 已最小化
字体
- 使用字体替换(https://developer.mozilla.org/en-US/docs/Web/CSS/@font-face/font-display)
- 使用来自 CDN 的字体
- 仅下载必要的字体
- 尽可能使用子集字体(https://developers.google.com/fonts/docs/getting_started#specifying_script_subsets)
脚本
- 客户端上仅包含交互元素(https://medium.com/@luke_schmuke/how-we-achieved-the-best-web-performance-with-partial-hydration-20fab9c808d5)
- 仅将使用过的JavaScript 发送到客户端(https://web.dev/codelab-remove-unused-code/,https://developers.google.com/web/fundamentals/performance/optimizing-javascript/tree-shaking)
- 考虑使用 Preact 代替 React(https://dev.to/dlw/next-js-replace-react-with-preact-2i72)
- JavaScript 已最小化
- 脚本使用以下方式压缩
- GZip(好)
- 布罗特利(更好)
- JavaScript 包被拆分,以便于有效下载和解析
- 只有必要的 JavaScript 才会被阻止
- 使用 Web Worker 进行内存密集型操作
- 尽可能使用性能更高的库(或使用原生 JavaScript)(例如 Lodash 与 Underscore、Temporal API 与 Moment)
数据
- 仅获取您需要的数据(考虑使用 GraphQL)
- 没有 API 链(考虑使用 GraphQL)
- 最小化数据规范化(卸载到独立功能或后端)
第三方脚本
- 第三方脚本是非阻塞的(https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/loading-third-party-javascript)
- 使用资源提示来并行下载(https://developers.google.com/web/fundamentals/performance/optimizing-content-efficiency/loading-third-party-javascript)
感知表现
- UI 占位符用于加载状态
- 连接丢失会导致通知并显示之前的状态(https://www.apollographql.com/docs/react/data/queries/#previousdata)
- 当数据已发送但服务器尚未收到时,显示已完成的操作状态
- 防止内容跳跃/布局偏移
- 尽可能减少 DNS 解析和 SSL 协商时间(https://zoompf.com/blog/2014/12/optimizing-tls-handshake/)
测试与分析
- 在管道中识别出降低性能的 PR
- 测量前端性能(https://speedcurve.com/)
- 定期分析前端性能
- 分析结果转化为可操作的待办事项
尽可能多地实现这些功能有两个好处:转化率可能会提高,因为会有更多用户使用你的应用。此外,你还可以节省自己的成本:更少的下载量、更少的带宽,而且由于你可以从源站缓存,你还可以节省基础设施成本。
我确信这个列表并不完整,如果我遗漏了什么,请告诉我!
文章来源:https://dev.to/endymion1818/nextjs-performance-checklist-5gjb