前端性能优化完全指南
性能优化是提升用户体验的关键因素,本文将介绍从资源加载到运行时性能的全面优化策略。
加载性能优化
代码分割
// 路由级别的代码分割
const Dashboard = lazy(() => import('./pages/Dashboard'));
const Settings = lazy(() => import('./pages/Settings'));
// 组件级别的代码分割
const HeavyChart = lazy(() => import('./components/HeavyChart'));
图片优化
- 使用 WebP 格式替代 PNG/JPG
- 实现懒加载
- 使用响应式图片
<img
src="image.webp"
loading="lazy"
srcset="image-400.webp 400w, image-800.webp 800w"
sizes="(max-width: 600px) 400px, 800px"
/>
运行时性能优化
避免不必要的重渲染
import { memo, useMemo, useCallback } from 'react';
const ExpensiveComponent = memo(({ data }: { data: Item[] }) => {
const sortedData = useMemo(() => {
return [...data].sort((a, b) => a.priority - b.priority);
}, [data]);
const handleClick = useCallback(() => {
console.log('clicked');
}, []);
return <List items={sortedData} onClick={handleClick} />;
});
Virtual Scrolling
对于长列表,使用虚拟滚动只渲染可见区域的项目:
import { FixedSizeList } from 'react-window';
const Row = ({ index, style }) => (
<div style={style}>Row {index}</div>
);
const VirtualList = () => (
<FixedSizeList
height={600}
itemCount={10000}
itemSize={35}
width="100%"
>
{Row}
</FixedSizeList>
);
性能监控
使用 Chrome DevTools 和 Lighthouse 持续监控性能指标:
- First Contentful Paint (FCP)
- Largest Contentful Paint (LCP)
- Cumulative Layout Shift (CLS)
性能优化是一个持续的过程,需要定期测量和改进。
