Web性能优化完全指南:从加载到渲染的全方位优化 Web性能优化完全指南从加载到渲染的全方位优化大家好我是蔓蔓。性能优化是前端开发中非常重要的一环。今天我来和大家分享Web性能优化的完整指南。性能指标Core Web Vitalsconst coreWebVitals { LCP: Largest Contentful Paint, // 最大内容绘制 (2.5s) FID: First Input Delay, // 首次输入延迟 (100ms) CLS: Cumulative Layout Shift // 累积布局偏移 (0.1) };其他指标const otherMetrics { TTFB: Time to First Byte, // 首字节时间 FCP: First Contentful Paint, // 首次内容绘制 TTI: Time to Interactive, // 可交互时间 TBT: Total Blocking Time // 总阻塞时间 };加载优化资源优化!-- 使用现代图片格式 -- picture source srcsetimage.avif typeimage/avif source srcsetimage.webp typeimage/webp img srcimage.jpg altImage /picture !-- 图片懒加载 -- img srcplaceholder.jpg>// 路由懒加载 const Home () import(/* webpackChunkName: home */ ./pages/Home); const About () import(/* webpackChunkName: about */ ./pages/About); // 组件懒加载 const Chart React.lazy(() import(./Chart)); // 条件加载 if (needsFeature) { import(./feature).then(module { module.init(); }); }缓存策略// HTTP缓存头 // Cache-Control: max-age31536000, immutable // ETag: 123456 // Last-Modified: Wed, 21 Oct 2023 07:28:00 GMT // Service Worker缓存 self.addEventListener(fetch, (event) { event.respondWith( caches.match(event.request).then((cached) { const fetchPromise fetch(event.request).then((networkResponse) { caches.open(cache).then((cache) { cache.put(event.request, networkResponse.clone()); }); return networkResponse; }); return cached || fetchPromise; }) ); });运行时优化渲染优化/* 使用transform代替top/left */ .move { transform: translateX(100px); } /* 使用will-change提示浏览器 */ .will-change { will-change: transform, opacity; } /* 使用contain隔离渲染 */ .isolated { contain: layout paint size; }JavaScript优化// 防抖 function debounce(fn, delay 300) { let timer null; return function(...args) { clearTimeout(timer); timer setTimeout(() fn.apply(this, args), delay); }; } // 节流 function throttle(fn, limit 100) { let inThrottle false; return function(...args) { if (!inThrottle) { fn.apply(this, args); inThrottle true; setTimeout(() inThrottle false, limit); } }; } // 使用requestAnimationFrame function animate() { // 更新动画 requestAnimationFrame(animate); }内存优化// 及时清理事件监听器 function cleanup() { element.removeEventListener(click, handler); } // 避免内存泄漏 class Component { destroy() { this.timer clearInterval(this.timer); this.observer this.observer.disconnect(); } }监控与分析Lighthouse# 运行Lighthouse lighthouse https://example.com --view # 生成报告 lighthouse https://example.com --outputjson --output-pathreport.jsonPerformance API// 测量性能 const startTime performance.now(); // 执行操作 doSomething(); const endTime performance.now(); console.log(Time: ${endTime - startTime}ms); // 标记和测量 performance.mark(start); doSomething(); performance.mark(end); performance.measure(duration, start, end);总结Web性能优化需要从多个层面入手优化资源加载和缓存减少渲染阻塞优化JavaScript执行监控性能指标技术应当有温度更快的应用能提升用户体验。