闽公网安备 35020302035485号
.大量图片或资源加载阻塞
// 主线程
const worker = new Worker('compute.js');
worker.postMessage(data);
worker.onmessage = function(e) {
console.log('Result:', e.data);
};
// compute.js
self.onmessage = function(e) {
const result = heavyComputation(e.data);
self.postMessage(result);
};
2.2 函数节流与防抖// 防抖:连续触发时只执行最后一次
function debounce(func, wait) {
let timeout;
returnfunction() {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, arguments), wait);
};
}
// 节流:连续触发时每隔一段时间执行一次
function throttle(func, wait) {
let lastTime = 0;
returnfunction() {
const now = Date.now();
if (now - lastTime >= wait) {
func.apply(this, arguments);
lastTime = now;
}
};
}
// 堆代码 duidaima.com
// 使用示例
window.addEventListener('resize', throttle(handleResize, 200));
2.3 使用requestAnimationFrame优化动画function animate() {
// 动画逻辑
element.style.left = `${left}px`;
if (left < 500) {
requestAnimationFrame(animate);
}
}
requestAnimationFrame(animate);
三. DOM操作优化// 不推荐
element.style.width = '100px';
element.style.height = '200px';
element.style.backgroundColor = 'red';
// 推荐:添加CSS类
.element-active {
width: 100px;
height: 200px;
background-color: red;
}
element.classList.add('element-active');
3.2 使用文档片段减少DOM操作// 创建文档片段
const fragment = document.createDocumentFragment();
// 批量添加元素
for (let i = 0; i < 1000; i++) {
const li = document.createElement('li');
li.textContent = `Item ${i}`;
fragment.appendChild(li);
}
// 一次性添加到DOM
document.getElementById('list').appendChild(fragment);
3.3 虚拟DOM技术// 添加监听器
element.addEventListener('click', onClick);
// 需要时移除
element.removeEventListener('click', onClick);
4.2 使用弱引用const weakMap = new WeakMap();
const element = document.getElementById('myElement');
weakMap.set(element, someData);
五. 资源加载优化const lazyImages = document.querySelectorAll('img.lazy');
const imageObserver = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src;
img.classList.remove('lazy');
imageObserver.unobserve(img);
}
});
});
lazyImages.forEach(img => imageObserver.observe(img));
5.2 代码分割与懒加载// 动态导入
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function MyComponent() {
return (
<div>
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
</div>
);
}
六. 性能监控与分析// 测量代码执行时间
const startTime = performance.now();
// 执行代码
doSomething();
const endTime = performance.now();
console.log(`执行时间: ${endTime - startTime}毫秒`);
七. 使用Web API优化function processTask(deadline) {
while (deadline.timeRemaining() > 0 && tasks.length > 0) {
processNextTask();
}
if (tasks.length > 0) {
requestIdleCallback(processTask);
}
}
requestIdleCallback(processTask);
总结