前端性能优化全攻略
前端性能直接影响用户体验和业务转化率。研究表明,页面加载时间每增加1秒,转化率就会下降7%。本文将系统地介绍前端性能优化的各个方面,从加载优化到渲染优化,全面提升页面性能。
一、加载优化
// 资源压缩与合并
// Webpack配置
module.exports = {
optimization: {
splitChunks: {
chunks: "all",
cacheGroups: {
vendor: {
test: /node_modules/,
name: "vendor",
priority: 10
}
}
}
}
}
// 图片优化
// 1. 使用WebP格式(体积减少30%)
// 2. 响应式图片
// <picture>
// <source srcset="img.webp" type="image/webp">
// <img src="img.jpg" loading="lazy">
// </picture>
// 3. 懒加载
document.addEventListener("DOMContentLoaded", function() {
var lazyImages = document.querySelectorAll("img[data-src]");
var observer = new IntersectionObserver(function(entries) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
var img = entry.target;
img.src = img.dataset.src;
observer.unobserve(img);
}
});
});
lazyImages.forEach(function(img) { observer.observe(img); });
});
二、渲染优化
// 关键渲染路径优化
// 1. CSS放在head,JS放在body底部或使用defer/async
// <script src="app.js" defer></script>
// <script src="analytics.js" async></script>
// 2. 避免强制同步布局
// 错误:读写交替
element.style.width = "100px";
var height = element.offsetHeight; // 触发重排!
element.style.height = height + "px";
// 正确:批量读,批量写
var height = element.offsetHeight; // 先读
element.style.width = "100px"; // 后写
element.style.height = height + "px";
// 3. 使用requestAnimationFrame
function animate() {
element.style.transform = "translateX(" + x + "px)";
requestAnimationFrame(animate);
}
requestAnimationFrame(animate);
// 4. 虚拟滚动(大列表优化)
// 只渲染可视区域内的元素
var visibleItems = items.slice(startIndex, endIndex);
container.innerHTML = visibleItems.map(renderItem).join("");
三、缓存策略
// Service Worker缓存
var CACHE_NAME = "app-v1";
var CACHE_URLS = [
"/", "/styles.css", "/app.js", "/logo.png"
];
self.addEventListener("install", function(event) {
event.waitUntil(
caches.open(CACHE_NAME).then(function(cache) {
return cache.addAll(CACHE_URLS);
})
);
});
self.addEventListener("fetch", function(event) {
event.respondWith(
caches.match(event.request).then(function(response) {
return response || fetch(event.request);
})
);
});
// HTTP缓存头
// 强缓存:
Cache-Control: max-age=31536000, immutable
// 协商缓存:
ETag: "abc123"
Last-Modified: Wed, 01 Jan 2024 00:00:00 GMT
四、性能监控
// Web Vitals
var observer = new PerformanceObserver(function(list) {
list.getEntries().forEach(function(entry) {
console.log({
name: entry.name, // 指标名
startTime: entry.startTime,
duration: entry.duration,
value: entry.value || entry.duration
});
});
});
// 监控关键指标
observer.observe({ entryTypes: ["largest-contentful-paint"] }); // LCP
observer.observe({ entryTypes: ["first-input"] }); // FID
observer.observe({ entryTypes: ["layout-shift"] }); // CLS
observer.observe({ entryTypes: ["paint"] }); // FCP
前端性能优化是一个系统工程,需要从网络、渲染、缓存等多个维度综合考虑。建议建立性能监控体系,持续关注Core Web Vitals指标,将性能优化作为日常开发的一部分。