性能优化:前端加载性能优化指南
大家好,我是欧阳瑞(Rich Own)。今天想和大家聊聊前端性能优化这个重要话题。作为一个全栈开发者,页面加载速度直接影响用户体验和转化率。今天就来分享一下前端加载性能优化的最佳实践。
性能优化概述
核心指标
| 指标 | 说明 | 目标值 |
|---|---|---|
| LCP | 最大内容绘制 | < 2.5s |
| FID | 首次输入延迟 | < 100ms |
| CLS | 累积布局偏移 | < 0.1 |
| FCP | 首次内容绘制 | < 1.8s |
优化方向
资源优化 → 压缩、合并、缓存
代码优化 → 懒加载、代码分割
渲染优化 → 关键渲染路径优化
网络优化 → CDN、HTTP/2、缓存策略
资源优化
图片优化
html
<!-- 使用合适的图片格式 -->
<img src="image.webp" alt="..." />
<img src="image.jpg" alt="..." />
<!-- 使用srcset -->
<img
src="image-small.jpg"
srcset="image-small.jpg 400w, image-medium.jpg 800w, image-large.jpg 1200w"
sizes="(max-width: 600px) 400px, (max-width: 1000px) 800px, 1200px"
alt="..."
/>
<!-- 使用WebP/AVIF -->
<picture>
<source srcset="image.avif" type="image/avif" />
<source srcset="image.webp" type="image/webp" />
<img src="image.jpg" alt="..." />
</picture>
CSS优化
css
/* 移除未使用的CSS */
/* 使用PurgeCSS自动清理 */
/* 关键CSS内联 */
<style>
.critical { /* 首屏需要的样式 */ }
</style>
/* 使用CSS变量 */
:root {
--primary-color: #3b82f6;
--font-size: 16px;
}
JavaScript优化
javascript
// 代码分割
const HeavyComponent = React.lazy(() => import('./HeavyComponent'));
// 懒加载
const lazyLoad = () => {
const images = document.querySelectorAll('img[data-src]');
const observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
observer.unobserve(img);
}
});
});
images.forEach(img => observer.observe(img));
};
渲染优化
关键渲染路径
html
<!-- 优化CSS加载 -->
<link rel="stylesheet" href="styles.css" media="print" onload="this.media='all'">
<noscript><link rel="stylesheet" href="styles.css"></noscript>
<!-- 优化字体加载 -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
<!-- 减少阻塞渲染 -->
<script defer src="script.js"></script>
<script async src="analytics.js"></script>
服务端渲染
javascript
// Next.js SSR示例
export async function getServerSideProps(context) {
const res = await fetch('https://api.example.com/data');
const data = await res.json();
return {
props: { data }
};
}
function Page({ data }) {
return <div>{data.content}</div>;
}
export default Page;
缓存策略
HTTP缓存
javascript
// 设置缓存头
app.use((req, res, next) => {
// 静态资源缓存1年
if (req.path.match(/\.(js|css|png|jpg)$/)) {
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
}
// API响应缓存5分钟
if (req.path.match(/^\/api/)) {
res.setHeader('Cache-Control', 'public, max-age=300');
}
next();
});
Service Worker缓存
javascript
// service-worker.js
const CACHE_NAME = 'my-app-cache-v1';
const ASSETS_TO_CACHE = [
'/',
'/index.html',
'/styles.css',
'/app.js'
];
self.addEventListener('install', (event) => {
event.waitUntil(
caches.open(CACHE_NAME).then((cache) => {
return cache.addAll(ASSETS_TO_CACHE);
})
);
});
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request).then((response) => {
return response || fetch(event.request);
})
);
});
实战案例:性能监控
javascript
// 使用Lighthouse监控
const { Lighthouse } = require('lighthouse');
async function runLighthouse(url) {
const lighthouse = await Lighthouse(url, {
chromeFlags: ['--headless'],
onlyCategories: ['performance']
});
console.log('Performance score:', lighthouse.lhr.categories.performance.score);
}
// 使用Web Vitals API
import { getCLS, getFID, getLCP } from 'web-vitals';
function sendToAnalytics(metric) {
const body = JSON.stringify(metric);
navigator.sendBeacon('/analytics', body);
}
getCLS(sendToAnalytics);
getFID(sendToAnalytics);
getLCP(sendToAnalytics);
最佳实践
1. 资源预加载
html
<!-- 预加载关键资源 -->
<link rel="preload" href="critical.js" as="script">
<link rel="preload" href="critical.css" as="style">
<link rel="preload" href="image.jpg" as="image">
<!-- 预连接 -->
<link rel="preconnect" href="https://api.example.com">
<link rel="preconnect" href="https://fonts.googleapis.com">
2. 代码优化
javascript
// 优化重排重绘
function updateElement(element, text) {
element.textContent = text;
}
// 使用requestAnimationFrame
function animate() {
requestAnimationFrame(() => {
// 执行动画
});
}
总结
前端性能优化是一个持续的过程。通过资源优化、渲染优化和缓存策略,可以显著提升页面加载速度和用户体验。
我的鬃狮蜥Hash对性能优化也有自己的理解------它总是用最快的速度捕捉蟋蟀,这也许就是自然界的"性能优化"吧!
如果你对前端性能优化有任何问题,欢迎留言交流!我是欧阳瑞,极客之路,永无止境!
技术栈:性能优化 · 前端优化 · Core Web Vitals