【前端】前端浏览器性能优化的小方法
前端浏览器性能优化是一个系统工程,涵盖了从加载到渲染的各个环节。以下是全面的优化方案:
一、资源加载优化
1. 减少HTTP请求
// 使用雪碧图 CSS Sprites
.icon {background-image: url('sprite.png');background-position: -0px -20px;
}// 内联小图片(Base64)
.logo {background: url('data:image/svg+xml;base64,PHN2Zy...');
}
2. 资源压缩与优化
<!-- 压缩资源 -->
<script src="app.min.js"></script>
<link rel="stylesheet" href="style.min.css"><!-- WebP格式图片 -->
<picture><source srcset="image.webp" type="image/webp"><source srcset="image.jpg" type="image/jpeg"><img src="image.jpg" alt="示例图片">
</picture>
3. 缓存策略
// Service Worker 缓存
self.addEventListener('fetch', (event) => {event.respondWith(caches.match(event.request).then(response => response || fetch(event.request)));
});
二、JavaScript 优化
1. 代码分割与懒加载
// 动态导入 - Webpack
const module = await import('./module.js');// React.lazy
const LazyComponent = React.lazy(() => import('./LazyComponent'));// 路由级别代码分割
const Home = lazy(() => import('./pages/Home'));
const About = lazy(() => import('./pages/About'));
2. 防抖与节流
// 防抖
function debounce(func, wait) {let timeout;return function executedFunction(...args) {const later = () => {clearTimeout(timeout);func(...args);};clearTimeout(timeout);timeout = setTimeout(later, wait);};
}// 节流
function throttle(func, limit) {let inThrottle;return function(...args) {if (!inThrottle) {func.apply(this, args);inThrottle = true;setTimeout(() => inThrottle = false, limit);}};
}// 使用
window.addEventListener('resize', throttle(handleResize, 250));
searchInput.addEventListener('input', debounce(handleSearch, 300));
3. 事件委托
// 不好的做法
document.querySelectorAll('.item').forEach(item => {item.addEventListener('click', handleClick);
});// 好的做法 - 事件委托
document.getElementById('list').addEventListener('click', (event) => {if (event.target.classList.contains('item')) {handleClick(event);}
});
三、CSS 优化
1. 选择器性能
/* 不好的选择器 */
div#container ul li a { ... }/* 好的选择器 */
.nav-link { ... }/* 避免重排重绘 */
.transform-element {transform: translateX(100px); /* 使用合成层 */will-change: transform; /* 提示浏览器 */
}
2. 关键CSS内联
<head><style>/* 关键CSS内联 */.header { position: fixed; top: 0; }.hero { height: 100vh; }</style>
</head>
四、渲染性能优化
1. 虚拟列表
// 大数据列表优化
function VirtualList({ items, itemHeight, containerHeight }) {const [scrollTop, setScrollTop] = useState(0);const visibleStart = Math.floor(scrollTop / itemHeight);const visibleEnd = Math.min(visibleStart + Math.ceil(containerHeight / itemHeight) + 1,items.length);const visibleItems = items.slice(visibleStart, visibleEnd);return (<div style={{ height: containerHeight, overflow: 'auto' }}onScroll={(e) => setScrollTop(e.target.scrollTop)}><div style={{ height: items.length * itemHeight, position: 'relative' }}>{visibleItems.map((item, index) => (<divkey={visibleStart + index}style={{position: 'absolute',top: (visibleStart + index) * itemHeight,height: itemHeight}}>{item.content}</div>))}</div></div>);
}
2. 使用 Web Workers
// main.js
const worker = new Worker('worker.js');worker.postMessage({ data: largeData });worker.onmessage = (event) => {console.log('Result:', event.data);
};// worker.js
self.onmessage = function(event) {const result = heavyCalculation(event.data);self.postMessage(result);
};
五、网络优化
1. 资源预加载
<!-- DNS 预解析 -->
<link rel="dns-prefetch" href="//api.example.com"><!-- 预加载关键资源 -->
<link rel="preload" href="critical-font.woff2" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="hero-image.jpg" as="image"><!-- 预连接 -->
<link rel="preconnect" href="https://cdn.example.com">
2. CDN 与 HTTP/2
<!-- 使用CDN -->
<script src="https://cdn.example.com/react@18/umd/react.production.min.js"></script><!-- HTTP/2 服务器推送 -->
<!-- 在服务器配置 -->
六、监控与性能测量
1. Performance API
// 性能测量
const measurePageLoad = () => {const [navigation] = performance.getEntriesByType('navigation');console.log('TTFB:', navigation.responseStart - navigation.requestStart);console.log('DOM Content Loaded:', navigation.domContentLoadedEventEnd - navigation.fetchStart);console.log('Full Load:', navigation.loadEventEnd - navigation.fetchStart);
};// 用户关键指标
const observer = new PerformanceObserver((list) => {for (const entry of list.getEntries()) {console.log('LCP:', entry.startTime);}
});
observer.observe({ entryTypes: ['largest-contentful-paint'] });
2. 真实用户监控 (RUM)
// Core Web Vitals
import { getCLS, getFID, getFCP, getLCP, getTTFB } from 'web-vitals';getCLS(console.log);
getFID(console.log);
getLCP(console.log);
七、现代优化技术
1. 图片懒加载
<img src="placeholder.jpg" data-src="real-image.jpg" loading="lazy"alt="示例图片"class="lazyload"
>
// 交叉观察器实现懒加载
const lazyImages = document.querySelectorAll('img.lazyload');const imageObserver = new IntersectionObserver((entries, observer) => {entries.forEach(entry => {if (entry.isIntersecting) {const img = entry.target;img.src = img.dataset.src;img.classList.remove('lazyload');imageObserver.unobserve(img);}});
});lazyImages.forEach(img => imageObserver.observe(img));
2. 预渲染和SSG
// Next.js 静态生成
export async function getStaticProps() {const data = await fetchData();return {props: { data },revalidate: 60 // ISR: 60秒重新生成};
}
八、构建工具优化
Webpack 配置示例
// webpack.config.js
module.exports = {optimization: {splitChunks: {chunks: 'all',cacheGroups: {vendor: {test: /[\\/]node_modules[\\/]/,name: 'vendors',chunks: 'all',},},},},plugins: [new BundleAnalyzerPlugin(),new CompressionPlugin({algorithm: 'gzip',}),],
};
这些优化措施需要根据具体项目情况选择实施,建议使用 Lighthouse 等工具定期检测性能,持续优化。
