前端性能优化技巧大全
前端性能直接影响用户体验和商业转化率。研究表明,页面加载时间每增加1秒,转化率就会下降7%。Google也将页面速度作为搜索排名的因素之一。本文将从网络层、渲染层、代码层三个维度,系统地介绍前端性能优化的策略和具体实施方法。
一、网络层优化
1. 减少HTTP请求
每个HTTP请求都有建立连接的开销,减少请求数是最直接的优化手段:
// CSS Sprites合并小图标
.icon { background: url("sprites.png") no-repeat; }
.icon-home { background-position: 0 0; }
.icon-user { background-position: -20px 0; }
// 内联小资源(小于10KB)
// 使用Base64编码直接嵌入CSS
// 合并CSS/JS文件
// 开发时分离,构建时合并压缩
2. 使用CDN加速
3. 资源压缩
// Nginx开启Gzip压缩
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml;
gzip_min_length 1024;
// 图片压缩:使用WebP格式
二、渲染层优化
1. 关键渲染路径优化
2. 图片懒加载
// 使用Intersection Observer实现懒加载
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
img.classList.remove("lazy");
observer.unobserve(img);
}
});
});
document.querySelectorAll("img.lazy").forEach(img => {
observer.observe(img);
});
// HTML

3. 虚拟列表
当页面需要渲染大量列表数据时,只渲染可视区域内的元素:
class VirtualList {
constructor(container, items, itemHeight) {
this.container = container;
this.items = items;
this.itemHeight = itemHeight;
this.visibleCount = Math.ceil(container.clientHeight / itemHeight);
this.totalHeight = items.length * itemHeight;
this.render();
}
onScroll(scrollTop) {
const startIndex = Math.floor(scrollTop / this.itemHeight);
const endIndex = startIndex + this.visibleCount + 2;
this.renderItems(startIndex, endIndex);
}
}
三、代码层优化
1. 防抖与节流
// 防抖 - 事件停止触发后执行
function debounce(fn, delay) {
let timer;
return function(...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
// 节流 - 固定频率执行
function throttle(fn, interval) {
let lastTime = 0;
return function(...args) {
const now = Date.now();
if (now - lastTime >= interval) {
fn.apply(this, args);
lastTime = now;
}
};
}
// 应用场景
window.addEventListener("resize", debounce(handleResize, 200));
window.addEventListener("scroll", throttle(handleScroll, 100));
2. DOM操作优化
// 批量DOM更新
const fragment = document.createDocumentFragment();
items.forEach(item => {
const li = document.createElement("li");
li.textContent = item.name;
fragment.appendChild(li);
});
list.appendChild(fragment); // 一次性插入
// 使用CSS动画替代JS动画
.element {
transform: translateX(0);
transition: transform 0.3s ease;
will-change: transform; /* 提示浏览器优化 */
}
四、缓存策略
// Service Worker缓存
self.addEventListener("fetch", event => {
event.respondWith(
caches.match(event.request).then(response => {
return response || fetch(event.request).then(fetchResponse => {
return caches.open("v1").then(cache => {
cache.put(event.request, fetchResponse.clone());
return fetchResponse;
});
});
})
);
});
// HTTP缓存头
Cache-Control: max-age=31536000 // 静态资源强缓存
Cache-Control: no-cache // 协商缓存
ETag: "abc123"
五、性能监控
// 使用Performance API监控关键指标
const [entry] = performance.getEntriesByType("navigation");
console.log("DOM加载:", entry.domContentLoadedEventEnd - entry.startTime);
console.log("完全加载:", entry.loadEventEnd - entry.startTime);
// Core Web Vitals监控
new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
console.log("LCP:", entry.startTime); // 最大内容绘制
}
}).observe({ type: "largest-contentful-paint", buffered: true });
前端性能优化是一个系统工程,需要从多个层面协同发力。建议先使用Lighthouse和WebPageTest等工具进行性能审计,找出最大的瓶颈,然后按照收益从大到小逐一优化。记住,优化的最终目标是提升用户体验,而不是追求某个分数。
