Web Workers 是瀏覽器提供的 JavaScript 多線程解決方案,允許在主線程之外運行腳本,解決復(fù)雜計算導(dǎo)致的頁面卡頓問題。本文主要講解Web Workers 的核心原理及使用場景和進階技巧。一、核心機制
1. 線程模型
主線程:負責(zé) UI 渲染、事件響應(yīng)(不可阻塞)
Worker 線程:執(zhí)行耗時任務(wù)(如大數(shù)據(jù)處理),與主線程并行運行
通信方式:通過 postMessage
傳遞數(shù)據(jù)(數(shù)據(jù)拷貝而非共享內(nèi)存)
2. 特性限制
二、基礎(chǔ)使用
1. 創(chuàng)建專用 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 大應(yīng)用場景
1. 復(fù)雜計算
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. 大數(shù)據(jù)分析
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. 實時數(shù)據(jù)流處理
const ws = new WebSocket('wss://api.example.com/stream');
ws.onmessage = (event) => {
worker.postMessage(JSON.parse(event.data));
};
5. 定時任務(wù)調(diào)度
let count = 0;
function preciseTimer() {
count++;
self.postMessage(count);
setTimeout(preciseTimer, 1000);
}
preciseTimer();
四、進階技巧
1. 傳輸大內(nèi)存數(shù)據(jù)(Transferable Objects)
避免數(shù)據(jù)拷貝,直接轉(zhuǎn)移內(nèi)存所有權(quán):
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
共享內(nèi)存 + 原子操作(需 HTTPS 環(huán)境):
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.數(shù)據(jù)序列化成本:頻繁傳遞大對象時優(yōu)先使用 Transferable Objects
2.生命周期管理:及時調(diào)用 terminate()
避免內(nèi)存泄漏
3.兼容性策略:
if (window.Worker) {
} else {
}
4.調(diào)試技巧:Chrome DevTools → Sources → Threads 可調(diào)試 Worker
學(xué)會 Web Workers 能顯著提升 Web 應(yīng)用的響應(yīng)速度和復(fù)雜任務(wù)處理能力,合理使用可突破單線程限制,打造更專業(yè)的瀏覽器端應(yīng)用。
閱讀原文:原文鏈接
該文章在 2025/3/25 10:30:33 編輯過