代码执行优化
JavaScript执行优化
// 1. 避免重复DOM查询
// 慢的方式
document.querySelector('.element').style.color = 'red';
document.querySelector('.element').style.fontSize = '14px';
// 快的方式
const element = document.querySelector('.element');
element.style.color = 'red';
element.style.fontSize = '14px';
// 2. 使用事件委托
// 慢
document.querySelectorAll('.item').forEach(item => {
item.addEventListener('click', handler);
});
// 快
document.querySelector('.container').addEventListener('click', (e) => {
if (e.target.classList.contains('item')) {
handler(e);
}
});
// 3. 节流和防抖
function throttle(func, delay) {
let lastCall = 0;
return function(...args) {
const now = Date.now();
if (now - lastCall >= delay) {
lastCall = now;
func.apply(this, args);
}
};
}
function debounce(func, delay) {
let timeout;
return function(...args) {
clearTimeout(timeout);
timeout = setTimeout(() => func.apply(this, args), delay);
};
}
网络请求优化
批量请求
// 合并多个请求
async function batchRequests(urls, batchSize = 5) {
const results = [];
for (let i = 0; i < urls.length; i += batchSize) {
const batch = urls.slice(i, i + batchSize);
const batchPromises = batch.map(url => fetch(url));
const batchResults = await Promise.all(batchPromises);
results.push(...batchResults);
}
return results;
}
// 使用缓存
const requestCache = new Map();
async function cachedFetch(url, options = {}) {
const cacheKey = `${url}_${JSON.stringify(options)}`;
if (requestCache.has(cacheKey)) {
return requestCache.get(cacheKey);
}
const response = await fetch(url, options);
const data = await response.json();
requestCache.set(cacheKey, data);
// 设置缓存过期时间
setTimeout(() => {
requestCache.delete(cacheKey);
}, 5 * 60 * 1000); // 5分钟
return data;
}
Web Workers优化
// 主线程
const worker = new Worker('worker.js');
worker.postMessage({
type: 'processData',
data: largeDataset
});
worker.onmessage = (e) => {
console.log('处理完成:', e.data);
};
// worker.js
self.onmessage = function(e) {
if (e.data.type === 'processData') {
// 处理耗时操作
const result = processLargeData(e.data.data);
self.postMessage(result);
}
};
function processLargeData(data) {
// 复杂计算逻辑
return data.map(item => ({
...item,
processed: true
}));
}
渲染优化
/* 使用CSS加速渲染 */
.element {
/* 启用GPU加速 */
transform: translateZ(0);
will-change: transform, opacity;
/* 避免重排 */
position: absolute;
opacity: 0;
transition: opacity 0.3s ease;
}
/* 虚拟滚动容器 */
.virtual-scroll {
height: 500px;
overflow-y: auto;
position: relative;
}
.virtual-item {
position: absolute;
width: 100%;
box-sizing: border-box;
}
// 虚拟滚动实现
class VirtualScroll {
constructor(container, itemHeight, totalItems) {
this.container = container;
this.itemHeight = itemHeight;
this.totalItems = totalItems;
this.visibleItems = Math.ceil(container.clientHeight / itemHeight);
this.buffer = 5;
this.render();
container.addEventListener('scroll', this.handleScroll.bind(this));
}
handleScroll() {
const scrollTop = this.container.scrollTop;
const startIndex = Math.max(0, Math.floor(scrollTop / this.itemHeight) - this.buffer);
const endIndex = Math.min(this.totalItems, startIndex + this.visibleItems + this.buffer * 2);
this.renderItems(startIndex, endIndex);
}
}
数据库优化
// IndexedDB优化
async function optimizeIndexedDB() {
const db = await openDB('clawDB', 1, {
upgrade(db) {
// 创建带索引的表
const store = db.createObjectStore('data', { keyPath: 'id' });
store.createIndex('timestamp', 'timestamp');
store.createIndex('category', 'category');
}
});
// 批量操作
const tx = db.transaction('data', 'readwrite');
const store = tx.objectStore('data');
const batch = Array(1000).fill().map((_, i) => ({
id: i,
data: `item${i}`,
timestamp: Date.now()
}));
const promises = batch.map(item => store.put(item));
await Promise.all(promises);
}
内存管理
// 避免内存泄漏
class DataProcessor {
constructor() {
this.data = new Map();
this.listeners = new Set();
}
// 使用WeakMap避免内存泄漏
privateData = new WeakMap();
cleanup() {
this.data.clear();
this.listeners.clear();
// 移除事件监听器
window.removeEventListener('resize', this.handleResize);
// 清理定时器
if (this.interval) {
clearInterval(this.interval);
}
// 断开Observers
if (this.observer) {
this.observer.disconnect();
}
}
}
构建优化配置
Webpack配置优化
// webpack.config.js
module.exports = {
mode: 'production',
optimization: {
splitChunks: {
chunks: 'all',
minSize: 20000,
maxSize: 244000,
},
minimize: true,
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
plugins: ['@babel/plugin-transform-runtime']
}
}
}
]
}
};
监控和性能分析
// 性能监控
class PerformanceMonitor {
constructor() {
this.metrics = {};
this.startTime = performance.now();
}
startMark(name) {
performance.mark(`${name}-start`);
}
endMark(name) {
performance.mark(`${name}-end`);
performance.measure(name, `${name}-start`, `${name}-end`);
const duration = performance.getEntriesByName(name)[0].duration;
this.metrics[name] = duration;
// 清理性能条目
performance.clearMarks(`${name}-start`);
performance.clearMarks(`${name}-end`);
performance.clearMeasures(name);
return duration;
}
logMetrics() {
console.table(this.metrics);
}
// 监控长任务
observeLongTasks() {
if ('PerformanceObserver' in window) {
const observer = new PerformanceObserver((list) => {
list.getEntries().forEach(entry => {
if (entry.duration > 50) { // 超过50ms的长任务
console.warn('长任务:', entry);
}
});
});
observer.observe({ entryTypes: ['longtask'] });
}
}
}
关键优化建议
- 代码分割:按需加载模块
- 懒加载:图片、组件等资源的懒加载
- 预加载:关键资源的预加载
- 服务端渲染:对于首屏内容
- CDN加速:静态资源使用CDN
- HTTP/2:启用HTTP/2协议
- 压缩资源:Gzip/Brotli压缩
- 图片优化:WebP格式、懒加载、响应式图片
快速优化检查清单
// 快速检查函数
function performanceCheck() {
// 检查DOM操作
console.log('DOM节点数量:', document.getElementsByTagName('*').length);
// 检查事件监听器
console.log('事件监听器数量:',
Array.from(document.querySelectorAll('*'))
.reduce((acc, node) =>
acc + (node.__events ? Object.keys(node.__events).length : 0), 0));
// 检查内存使用
if (window.performance && performance.memory) {
console.log('内存使用:',
Math.round(performance.memory.usedJSHeapSize / 1024 / 1024) + 'MB');
}
// Lighthouse模拟检查
const checks = {
'首字节时间': performance.timing.responseStart - performance.timing.navigationStart,
'DOM加载完成': performance.timing.domContentLoadedEventEnd - performance.timing.navigationStart,
'页面完全加载': performance.timing.loadEventEnd - performance.timing.navigationStart
};
console.table(checks);
}
这些优化措施可以根据OpenClaw的具体使用场景选择应用,建议先进行性能分析,找出瓶颈点,然后有针对性地进行优化。

版权声明:除非特别标注,否则均为本站原创文章,转载时请以链接形式注明文章出处。