When to Use
- Parsing or manipulating massive JSON datasets.
- Client-side image processing, video encoding, or audio manipulation.
- Complex mathematical calculations (e.g. cryptography, physics engines).
- Formatting large rich-text documents.
When NOT to Use
- When the task involves manipulating the DOM directly.
- When the overhead of serializing/deserializing data via postMessage exceeds the cost of just running the task on the main thread.
- For simple UI state updates.
Code Examples
Offloading Heavy Processing
The heavyCalculation function completely freezes the worker thread, but the main thread remains untouched. The UI remains perfectly responsive.
// main.js
const worker = new Worker('worker.js');
worker.postMessage({ type: 'PROCESS_DATA', payload: massiveArray });
worker.onmessage = (e) => {
console.log('Processed data received:', e.data);
};
// worker.js
self.onmessage = (e) => {
if (e.data.type === 'PROCESS_DATA') {
const result = heavyCalculation(e.data.payload);
self.postMessage(result);
}
};