name: web-performance-optimization description: 通过代码分割、懒加载、缓存策略和Core Web Vitals监控来优化网页应用性能。当改进页面加载时间、实现服务工作者或减少包大小时使用。 license: MIT
Web性能优化
概述
实现性能优化策略,包括懒加载、代码分割、缓存、压缩和监控,以改善Core Web Vitals和用户体验。
何时使用
- 页面加载时间慢
- 高 Largest Contentful Paint (LCP)
- 大的包大小
- 频繁的 Cumulative Layout Shift (CLS)
- 移动性能问题
代码分割(React)
import { lazy, Suspense } from 'react';
import { Routes, Route } from 'react-router-dom';
const Home = lazy(() => import('./pages/Home'));
const Dashboard = lazy(() => import('./pages/Dashboard'));
const Settings = lazy(() => import('./pages/Settings'));
function App() {
return (
<Suspense fallback={<Loading />}>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/dashboard" element={<Dashboard />} />
<Route path="/settings" element={<Settings />} />
</Routes>
</Suspense>
);
}
Webpack包优化
// webpack.config.js
module.exports = {
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all'
}
}
}
}
};
图像优化
<picture>
<source srcset="image.webp" type="image/webp">
<source srcset="image.jpg" type="image/jpeg">
<img
src="image.jpg"
srcset="image-400.jpg 400w, image-800.jpg 800w, image-1200.jpg 1200w"
sizes="(max-width: 600px) 100vw, 50vw"
loading="lazy"
decoding="async"
alt="描述"
>
</picture>
服务工作者缓存
// sw.js
const CACHE_NAME = 'app-v1';
const ASSETS = ['/', '/index.html', '/main.js', '/styles.css'];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then(cache => cache.addAll(ASSETS))
);
});
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then(cached => {
return cached || fetch(event.request).then(response => {
return caches.open(CACHE_NAME).then(cache => {
cache.put(event.request, response.clone());
return response;
});
});
})
);
});
Core Web Vitals监控
// 追踪LCP、CLS、INP(注意:INP于2024年3月取代了FID)
// sendToAnalytics是一个占位函数,用于将指标发送到分析端点
// 预期签名:sendToAnalytics({ metric: string, value: number }) => void
// 示例实现:
function sendToAnalytics({ metric, value }) {
// 替换为您的分析实现(例如,Google Analytics、Segment)
fetch('/api/analytics', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ metric, value, timestamp: Date.now() })
});
}
// Largest Contentful Paint (LCP)
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log(`LCP: ${entry.startTime}ms`);
sendToAnalytics({ metric: 'LCP', value: entry.startTime });
}
}).observe({ type: 'largest-contentful-paint', buffered: true });
// Cumulative Layout Shift (CLS)
new PerformanceObserver((list) => {
let cls = 0;
for (const entry of list.getEntries()) {
if (!entry.hadRecentInput) cls += entry.value;
}
sendToAnalytics({ metric: 'CLS', value: cls });
}).observe({ type: 'layout-shift', buffered: true });
// Interaction to Next Paint (INP) - 取代FID
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
// INP测量响应性 - 最慢交互的持续时间
const inp = entry.processingEnd - entry.processingStart;
console.log(`INP: ${inp}ms`);
sendToAnalytics({ metric: 'INP', value: inp });
}
}).observe({ type: 'event', buffered: true }); // 'event' 捕获交互事件
性能目标
| 指标 | 良好 | 需要改进 |
|---|---|---|
| LCP | <2.5秒 | 2.5-4秒 |
| INP | <200毫秒 | 200-500毫秒 |
| CLS | <0.1 | 0.1-0.25 |
| TTI | <3.8秒 | 3.8-7.3秒 |
注意: INP(Interaction to Next Paint)于2024年3月取代FID(First Input Delay)成为Core Web Vital。INP通过捕获交互的完整持续时间,提供了更全面的页面响应性测量。
压缩(Nginx)
gzip on;
gzip_types text/plain text/css application/json application/javascript;
gzip_min_length 1000;
gzip_comp_level 6;
最佳实践
- 通过代码分割最小化包大小
- 使用适当格式优化图像
- 策略性地实现懒加载
- 使用HTTP缓存头
- 启用gzip/brotli压缩
- 持续监控Core Web Vitals
- 实现服务工作者
- 延迟非关键JavaScript
- 优化关键渲染路径
- 在真实设备和网络上测试
优化检查表
- [ ] 为路由启用代码分割
- [ ] 懒加载首屏以下组件
- [ ] 优化和压缩图像
- [ ] 实现服务工作者缓存
- [ ] 启用gzip/brotli压缩
- [ ] 监控Core Web Vitals
- [ ] 最小化渲染阻塞资源
额外配置
参见 references/compression-monitoring.md 获取:
- Webpack压缩插件设置
- Apache .htaccess压缩配置
- TTFB监控实现
- Puppeteer自动化测量
参见 references/typescript-advanced.md 获取:
- TypeScript懒加载工具
- TypeScript图像组件
- 高级服务工作者与离线回退
- TerserPlugin配置
- 完整PerformanceMetrics接口
工具
- Lighthouse / PageSpeed Insights
- WebPageTest
- Chrome DevTools性能标签
- web-vitals npm包