Web性能优化完全指南:从加载到渲染的全方位优化
大家好,我是蔓蔓。性能优化是前端开发中非常重要的一环。今天我来和大家分享Web性能优化的完整指南。
性能指标
Core Web Vitals
javascript
const coreWebVitals = {
LCP: 'Largest Contentful Paint', // 最大内容绘制 (<=2.5s)
FID: 'First Input Delay', // 首次输入延迟 (<=100ms)
CLS: 'Cumulative Layout Shift' // 累积布局偏移 (<=0.1)
};
其他指标
javascript
const otherMetrics = {
TTFB: 'Time to First Byte', // 首字节时间
FCP: 'First Contentful Paint', // 首次内容绘制
TTI: 'Time to Interactive', // 可交互时间
TBT: 'Total Blocking Time' // 总阻塞时间
};
加载优化
资源优化
html
<!-- 使用现代图片格式 -->
<picture>
<source srcset="image.avif" type="image/avif">
<source srcset="image.webp" type="image/webp">
<img src="image.jpg" alt="Image">
</picture>
<!-- 图片懒加载 -->
<img src="placeholder.jpg" data-src="image.jpg" loading="lazy">
<!-- 字体预加载 -->
<link rel="preload" href="font.woff2" as="font" type="font/woff2">
<!-- 关键CSS内联 -->
<style>
.critical {
/* 关键样式 */
}
</style>
<!-- 非关键CSS异步加载 -->
<link rel="stylesheet" href="non-critical.css" media="print" onload="this.media='all'">
代码分割
javascript
// 路由懒加载
const Home = () => import(/* webpackChunkName: "home" */ './pages/Home');
const About = () => import(/* webpackChunkName: "about" */ './pages/About');
// 组件懒加载
const Chart = React.lazy(() => import('./Chart'));
// 条件加载
if (needsFeature) {
import('./feature').then(module => {
module.init();
});
}
缓存策略
javascript
// HTTP缓存头
// Cache-Control: max-age=31536000, immutable
// ETag: "123456"
// Last-Modified: Wed, 21 Oct 2023 07:28:00 GMT
// Service Worker缓存
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then((cached) => {
const fetchPromise = fetch(event.request).then((networkResponse) => {
caches.open('cache').then((cache) => {
cache.put(event.request, networkResponse.clone());
});
return networkResponse;
});
return cached || fetchPromise;
})
);
});
运行时优化
渲染优化
css
/* 使用transform代替top/left */
.move {
transform: translateX(100px);
}
/* 使用will-change提示浏览器 */
.will-change {
will-change: transform, opacity;
}
/* 使用contain隔离渲染 */
.isolated {
contain: layout paint size;
}
JavaScript优化
javascript
// 防抖
function debounce(fn, delay = 300) {
let timer = null;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
// 节流
function throttle(fn, limit = 100) {
let inThrottle = false;
return function(...args) {
if (!inThrottle) {
fn.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, limit);
}
};
}
// 使用requestAnimationFrame
function animate() {
// 更新动画
requestAnimationFrame(animate);
}
内存优化
javascript
// 及时清理事件监听器
function cleanup() {
element.removeEventListener('click', handler);
}
// 避免内存泄漏
class Component {
destroy() {
this.timer && clearInterval(this.timer);
this.observer && this.observer.disconnect();
}
}
监控与分析
Lighthouse
bash
# 运行Lighthouse
lighthouse https://example.com --view
# 生成报告
lighthouse https://example.com --output=json --output-path=report.json
Performance API
javascript
// 测量性能
const startTime = performance.now();
// 执行操作
doSomething();
const endTime = performance.now();
console.log(`Time: ${endTime - startTime}ms`);
// 标记和测量
performance.mark('start');
doSomething();
performance.mark('end');
performance.measure('duration', 'start', 'end');
总结
Web性能优化需要从多个层面入手:
- 优化资源加载和缓存
- 减少渲染阻塞
- 优化JavaScript执行
- 监控性能指标
技术应当有温度,更快的应用能提升用户体验。