JavaScript性能优化实战技术文章大纲
代码层面优化
避免全局变量污染,使用let
和const
替代var
,减少作用域链查找开销。
// 反例:全局变量
var globalVar = '低效';// 正例:局部变量
function optimized() {const localVar = '高效';
}
减少DOM操作,合并多次操作或使用文档片段(DocumentFragment
)。
// 反例:频繁操作DOM
for (let i = 0; i < 100; i++) {document.body.innerHTML += `<div>${i}</div>`;
}// 正例:使用文档片段
const fragment = document.createDocumentFragment();
for (let i = 0; i < 100; i++) {const div = document.createElement('div');div.textContent = i;fragment.appendChild(div);
}
document.body.appendChild(fragment);
事件处理优化
使用事件委托替代批量事件绑定,减少内存占用。
// 反例:为每个子元素绑定事件
document.querySelectorAll('.item').forEach(item => {item.addEventListener('click', handleClick);
});// 正例:事件委托
document.querySelector('.parent').addEventListener('click', (e) => {if (e.target.classList.contains('item')) {handleClick(e);}
});
防抖(Debounce)与节流(Throttle)控制高频事件触发频率。
// 防抖实现
function debounce(fn, delay) {let timer;return function() {clearTimeout(timer);timer = setTimeout(() => fn.apply(this, arguments), delay);};
}
数据加载与渲染优化
懒加载非关键资源(如图片、组件),使用Intersection Observer
API。
const observer = new IntersectionObserver((entries) => {entries.forEach(entry => {if (entry.isIntersecting) {const img = entry.target;img.src = img.dataset.src;observer.unobserve(img);}});
});
document.querySelectorAll('img.lazy').forEach(img => observer.observe(img));
虚拟列表(Virtual List)优化长列表渲染,仅渲染可视区域内容。
内存管理
及时清除定时器、事件监听器及无效引用,避免内存泄漏。
// 清除无效引用示例
let heavyObject = { data: new Array(1000000).fill('data') };
function cleanup() {heavyObject = null; // 手动释放内存
}
使用弱引用(WeakMap
/WeakSet
)存储临时数据。
工具与监控
利用Chrome DevTools
的Performance和Memory面板分析性能瓶颈。
集成Lighthouse
进行自动化性能评分与优化建议。
# 使用Lighthouse命令行工具
lighthouse https://example.com --view --output=html
编译与打包优化
通过Tree Shaking(如Webpack配置)移除未引用代码。
// webpack.config.js
module.exports = {mode: 'production',optimization: {usedExports: true,},
};
代码分割(Code Splitting)按需加载模块。
// 动态导入示例
import('./module').then(module => {module.run();
});