Web Workers 是浏览器提供的 JavaScript 多线程解决方案,允许在主线程之外运行脚本,解决复杂计算导致的页面卡顿问题。本文主要讲解Web Workers 的核心原理及使用场景和进阶技巧。一、核心机制
1. 线程模型
2. 特性限制
二、基础使用
1. 创建专用 Worker(Dedicated Worker)
主线程代码:
const worker = new Worker('worker.js');
worker.postMessage({ type: 'CALC', data: [1, 2, 3] });
worker.onmessage = (e) => {
console.log('Result:', e.data);
};
worker.onerror = (err) => {
console.error('Worker error:', err);
};
self.onmessage = function(e) {
if (e.data.type === 'CALC') {
const sum = e.data.data.reduce((a, b) => a + b, 0);
self.postMessage(sum);
}
};
2. 终止 Worker
worker.terminate();
self.close();
三、5 大应用场景
1. 复杂计算
worker.postMessage({ nums: Array(1e6).fill(Math.random()) });
self.onmessage = (e) => {
const sum = e.data.nums.reduce((acc, num) => acc + num, 0);
self.postMessage(sum);
};
2. 图像处理
canvas.addEventListener('imageUpload', (e) => {
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
worker.postMessage(imageData);
});
self.onmessage = (e) => {
const data = e.data.data;
for (let i = 0; i < data.length; i += 4) {
const avg = (data[i] + data[i+1] + data[i+2]) / 3;
data[i] = data[i+1] = data[i+2] = avg;
}
self.postMessage(e.data);
};
3. 大数据分析
self.onmessage = (e) => {
const rawData = e.data;
const results = rawData
.filter(item => item.age > 30)
.map(item => ({ ...item, score: item.value * 2 }));
self.postMessage(results);
};
4. 实时数据流处理
const ws = new WebSocket('wss://api.example.com/stream');
ws.onmessage = (event) => {
worker.postMessage(JSON.parse(event.data));
};
5. 定时任务调度
let count = 0;
function preciseTimer() {
count++;
self.postMessage(count);
setTimeout(preciseTimer, 1000);
}
preciseTimer();
四、进阶技巧
1. 传输大内存数据(Transferable Objects)
避免数据拷贝,直接转移内存所有权:
const buffer = new ArrayBuffer(1024 * 1024 * 100);
worker.postMessage(buffer, [buffer]);
2. Worker 池管理
class WorkerPool {
constructor(poolSize, workerScript) {
this.pool = Array(poolSize).fill().map(() => new Worker(workerScript));
this.taskQueue = [];
}
exec(data) {
return new Promise((resolve) => {
const worker = this.pool.find(w => !w.busy);
if (worker) {
worker.busy = true;
worker.postMessage(data);
worker.onmessage = (e) => {
worker.busy = false;
resolve(e.data);
};
} else {
this.taskQueue.push({ data, resolve });
}
});
}
}
3. SharedArrayBuffer + Atomics
共享内存 + 原子操作(需 HTTPS 环境):
const sab = new SharedArrayBuffer(1024);
const arr = new Int32Array(sab);
worker.postMessage(sab);
self.onmessage = (e) => {
const sharedArr = new Int32Array(e.data);
Atomics.add(sharedArr, 0, 1);
};
五、注意事项
1.数据序列化成本:频繁传递大对象时优先使用 Transferable Objects
2.生命周期管理:及时调用 terminate()
避免内存泄漏
3.兼容性策略:
if (window.Worker) {
} else {
}
4.调试技巧:Chrome DevTools → Sources → Threads 可调试 Worker
学会 Web Workers 能显著提升 Web 应用的响应速度和复杂任务处理能力,合理使用可突破单线程限制,打造更专业的浏览器端应用。
阅读原文:原文链接
该文章在 2025/3/25 10:30:33 编辑过