JavaScript性能优化实战
2025-07-06 01:27:20
38
JavaScript性能优化实战示例
1. 减少DOM操作
优化前:
for (let i = 0; i < 1000; i++) { document.getElementById('list').innerHTML += '<li>' + i + '</li>'; }
优化后:
let html = ''; for (let i = 0; i < 1000; i++) { html += '<li>' + i + '</li>'; } document.getElementById('list').innerHTML = html;
2. 事件委托
优化前:
document.querySelectorAll('li').forEach(item => { item.addEventListener('click', function() { console.log(this.textContent); }); });
优化后:
document.getElementById('list').addEventListener('click', function(e) { if (e.target.tagName === 'LI') { console.log(e.target.textContent); } });
3. 防抖与节流
防抖实现:
function debounce(func, delay) { let timer; return function() { clearTimeout(timer); timer = setTimeout(() => { func.apply(this, arguments); }, delay); }; } window.addEventListener('resize', debounce(function() { console.log('Window resized'); }, 300));
节流实现:
function throttle(func, limit) { let lastFunc; let lastRan; return function() { const context = this; const args = arguments; if (!lastRan) { func.apply(context, args); lastRan = Date.now(); } else { clearTimeout(lastFunc); lastFunc = setTimeout(function() { if ((Date.now() - lastRan) >= limit) { func.apply(context, args); lastRan = Date.now(); } }, limit - (Date.now() - lastRan)); } }; } window.addEventListener('scroll', throttle(function() { console.log('Scrolling'); }, 200));
4. 使用Web Workers处理耗时任务
主线程代码:
const worker = new Worker('worker.js'); worker.postMessage({data: largeArray}); worker.onmessage = function(e) { console.log('Result from worker:', e.data); };
worker.js:
self.onmessage = function(e) { const result = processLargeData(e.data); self.postMessage(result); }; function processLargeData(data) { // 耗时处理逻辑 return processedData; }
5. 使用requestAnimationFrame优化动画
优化前:
function animate() { element.style.left = (parseInt(element.style.left) + 1) + 'px'; setTimeout(animate, 16); } animate();
优化后:
function animate() { element.style.left = (parseInt(element.style.left) + 1) + 'px'; requestAnimationFrame(animate); } requestAnimationFrame(animate);
6. 内存管理优化
优化前:
function createObjects() { for (let i = 0; i < 10000; i++) { const obj = {id: i, data: new Array(1000).join('*')}; // 没有释放引用 } }
优化后:
function createObjects() { const objects = []; for (let i = 0; i < 10000; i++) { objects.push({id: i, data: new Array(1000).join('*')}); } // 使用后清除引用 objects.length = 0; }
7. 使用性能API监控
// 测量代码执行时间 performance.mark('start'); // 执行代码... performance.mark('end'); performance.measure('measureName', 'start', 'end'); const duration = performance.getEntriesByName('measureName')[0].duration; console.log(`执行耗时: ${duration}ms`);
8. 懒加载与代码分割
动态导入:
button.addEventListener('click', async () => { const module = await import('./heavyModule.js'); module.doSomething(); });
图片懒加载:
<img data-src="image.jpg" class="lazy" alt="Lazy loaded image"> <script> document.addEventListener('DOMContentLoaded', function() { const lazyImages = [].slice.call(document.querySelectorAll('img.lazy')); if ('IntersectionObserver' in window) { const lazyImageObserver = new IntersectionObserver(function(entries) { entries.forEach(function(