一、运行时性能优化
1. 主线程阻塞问题
- 优化策略:
- 任务分片:将长任务拆分为微任务队列
function processChunk(data, chunkSize, callback) { let index = 0; function next() { const end = Math.min(index + chunkSize, data.length); for (; index < end; index++) { // 处理数据 } if (index < data.length) { requestIdleCallback(next); // 或 setTimeout(next, 0) } else { callback(); } } next(); }
Web Workers:将CPU密集型任务(如图像处理)移至Worker
// main.js const worker = new Worker('task.js'); worker.postMessage(largeData); worker.onmessage = e => updateUI(e.data); // task.js self.onmessage = e => { const result = heavyCompute(e.data); self.postMessage(result); };
2. 内存泄漏定位
- 工具:Chrome DevTools Memory面板 > Heap Snapshot对比
- 典型场景:
- 未解绑的事件监听
- 闭包持有DOM引用
- 定时器未清除
- 解决方案:
// 弱引用避免内存泄漏 const map = new WeakMap(); function register(element) { const data = { clicks: 0 }; map.set(element, data); element.addEventListener('click', () => { data.clicks++; }); }
二、渲染性能优化
1. DOM操作优化
- 批量更新:使用DocumentFragment或虚拟DOM
const fragment = document.createDocumentFragment(); for (let i = 0; i < 1000; i++) { const div = document.createElement('div'); fragment.appendChild(div); } document.body.appendChild(fragment);
- 减少重排(Reflow):
- 使用
requestAnimationFrame
集中样式变更 - 读写分离:先读取布局属性,再批量写入
- 使用
-
2. 高频事件优化
- 防抖(Debounce)与节流(Throttle):
function throttle(fn, delay) { let lastCall = 0; return (...args) => { const now = Date.now(); if (now - lastCall >= delay) { fn.apply(this, args); lastCall = now; } }; } window.addEventListener('resize', throttle(updateLayout, 200));
三、网络与加载优化
1. 代码交付优化
- Tree Shaking:配置Rollup/Vite移除未使用代码
// rollup.config.js export default { plugins: [terser()], output: { format: 'esm' } };
按需加载:动态导入模块
document.getElementById('btn').addEventListener('click', async () => { const module = await import('./heavyModule.js'); module.run(); });
2. 缓存策略
- 长效缓存:文件名哈希 + Cache-Control头
# Nginx配置 location /static/ { expires 1y; add_header Cache-Control "public, immutable"; }
四、工具链与监控
1. 性能分析工具
- Lighthouse:生成性能评分与优化建议
npm install -g lighthouse lighthouse http://your-site.com --view
- Chrome Performance面板:定位长任务与强制布局抖动
- Performance Observer API
-
2. 运行时监控
-
const observer = new PerformanceObserver(list => { for (const entry of list.getEntries()) { if (entry.duration > 100) { console.warn('长任务:', entry); } } }); observer.observe({ entryTypes: ['longtask'] });
最佳实践:
- 使用
console.time
/performance.now()
量化关键路径耗时 - 优先优化高频执行路径(如滚动处理函数)
-
通过以上策略,可将JavaScript执行效率提升30%-200%,具体收益取决于应用场景与实现质量。
- 对第三方库进行按需引入与版本监控(如lodash-es代替lodash)
- 任务分片:将长任务拆分为微任务队列