部署上线
性能监控
了解应用性能和用户体验
性能直接影响用户体验和转化率。页面加载慢 1 秒,转化率下降 7%。
为什么需要性能监控
- 发现瓶颈:哪个页面/接口慢
- 用户体验:真实用户的加载速度
- 优化效果:验证优化是否有效
- 地域差异:不同地区的性能差异
核心指标
Web Vitals
Google 定义的三个核心指标:
-
LCP(Largest Contentful Paint)
- 最大内容绘制时间
- 目标:< 2.5 秒
- 影响:用户感知的加载速度
-
FID(First Input Delay)
- 首次输入延迟
- 目标:< 100 毫秒
- 影响:交互响应速度
-
CLS(Cumulative Layout Shift)
- 累积布局偏移
- 目标:< 0.1
- 影响:视觉稳定性
其他重要指标
- TTFB:首字节时间(服务器响应速度)
- FCP:首次内容绘制
- TTI:可交互时间
推荐工具
Vercel Analytics(推荐 Vercel 用户)
优点:
- 零配置(Vercel 项目自动启用)
- 真实用户数据
- 按地域/设备分析
- 免费
缺点:
- 只支持 Vercel
Google Analytics 4
优点:
- 免费
- 功能全面
- 结合用户行为分析
缺点:
- 配置复杂
- 数据延迟
Sentry Performance
优点:
- 结合错误追踪
- 详细的性能追踪
- 免费额度 10000 事件/月
缺点:
- 需要额外配置
快速开始:Vercel Analytics
1. 安装
npm install @vercel/analytics2. 配置
// app/layout.js (Next.js App Router)
import { Analytics } from '@vercel/analytics/react'
export default function RootLayout({ children }) {
return (
<html>
<body>
{children}
<Analytics />
</body>
</html>
)
}3. 查看数据
在 Vercel 项目后台 → Analytics 查看。
快速开始:Web Vitals
手动测量
import { onCLS, onFID, onLCP } from 'web-vitals'
onCLS(console.log)
onFID(console.log)
onLCP(console.log)发送到分析服务
import { onCLS, onFID, onLCP } from 'web-vitals'
function sendToAnalytics(metric) {
fetch('/api/analytics', {
method: 'POST',
body: JSON.stringify(metric),
})
}
onCLS(sendToAnalytics)
onFID(sendToAnalytics)
onLCP(sendToAnalytics)快速开始:Sentry Performance
配置
import * as Sentry from "@sentry/nextjs"
Sentry.init({
dsn: "your-dsn-here",
tracesSampleRate: 0.1, // 采样 10% 的请求
integrations: [
Sentry.browserTracingIntegration(),
],
})自定义追踪
const transaction = Sentry.startTransaction({
name: "Checkout Process",
})
// 执行操作
await processPayment()
transaction.finish()性能优化建议
图片优化
// Next.js Image 组件
import Image from 'next/image'
<Image
src="/hero.jpg"
width={800}
height={600}
alt="Hero"
priority // 首屏图片
/>代码分割
// 动态导入
const HeavyComponent = dynamic(() => import('./HeavyComponent'), {
loading: () => <p>Loading...</p>,
})字体优化
// next.config.js
module.exports = {
optimizeFonts: true,
}预加载关键资源
<link rel="preload" href="/critical.css" as="style">
<link rel="preload" href="/critical.js" as="script">监控 API 性能
记录 API 响应时间
// middleware.js
export function middleware(request) {
const start = Date.now()
const response = NextResponse.next()
const duration = Date.now() - start
console.log(`${request.url} - ${duration}ms`)
return response
}使用 Sentry
const transaction = Sentry.startTransaction({
op: "http.server",
name: "GET /api/users",
})
const span = transaction.startChild({
op: "db.query",
description: "SELECT * FROM users",
})
// 执行查询
const users = await db.query("SELECT * FROM users")
span.finish()
transaction.finish()真实用户监控 vs 合成监控
真实用户监控(RUM)
- 收集真实用户的性能数据
- 反映实际用户体验
- 工具:Vercel Analytics、Google Analytics
合成监控
- 定期从固定位置测试
- 发现性能回归
- 工具:Lighthouse CI、WebPageTest
Lighthouse CI
在 CI/CD 中自动运行 Lighthouse:
# .github/workflows/lighthouse.yml
name: Lighthouse CI
on: [push]
jobs:
lighthouse:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Run Lighthouse CI
uses: treosh/lighthouse-ci-action@v9
with:
urls: |
https://your-site.com
uploadArtifacts: true性能预算
设置性能目标,超出时告警:
// lighthouserc.js
module.exports = {
ci: {
assert: {
assertions: {
'first-contentful-paint': ['error', { maxNumericValue: 2000 }],
'largest-contentful-paint': ['error', { maxNumericValue: 2500 }],
'cumulative-layout-shift': ['error', { maxNumericValue: 0.1 }],
},
},
},
}常见性能问题
1. 图片未优化
- 使用 WebP 格式
- 压缩图片
- 使用 CDN
2. JavaScript 包太大
- 代码分割
- 移除未使用的依赖
- 使用 Tree Shaking
3. 字体加载慢
- 使用系统字体
- 字体子集化
- 使用
font-display: swap
4. 第三方脚本
- 延迟加载
- 使用 Web Worker
- 考虑是否真的需要
免费工具
- Lighthouse:Chrome 内置
- WebPageTest:详细的性能分析
- PageSpeed Insights:Google 的在线工具
- Vercel Analytics:Vercel 用户免费