Web Worker
About 319 wordsAbout 1 min
Web WorkerNative technology
2025-01-18
About Web Worker
Web Worker is a browser technology that allows running JavaScript code in an independent thread, avoiding blocking the main thread (UI thread). It is suitable for handling time-consuming computational tasks, such as data processing and complex algorithms, to improve page responsiveness.
Features of Web Worker
Independent thread
Cannot directly access DOM, window, document, or localStorage
Types of Workers Supported by Web Worker
Dedicated Worker
: Each worker can only be used by one main thread.Shared Worker
: Multiple main threads can share a worker, suitable for cross-page communication.self.onconnect = function (e) { const port = e.ports[0]; port.onmessage = function (event) { port.postMessage('Hello from Shared Worker'); }; }; const worker = new SharedWorker('sharedWorker.js'); worker.port.onmessage = function (e) { console.log(e.data); }; worker.port.postMessage('Hello');
Service Worker
:- Used to intercept network requests and implement offline caching.
- Does not directly communicate with the UI thread but uses postMessage or message channels. For more details, refer here
How to Load External Scripts in Web Worker
importScripts()
Pass scripts through the constructor
// main.js
const workerCode = `
onmessage = function(e) {
const { a, b, operation } = e.data;
let result;
if (operation === 'add') {
result = a + b;
} else if (operation === 'subtract') {
result = a - b;
}
postMessage(result); // Return result to the main thread
}
`;
const blob = new Blob([workerCode], { type: 'application/javascript' }); // Create Blob object
const worker = new Worker(URL.createObjectURL(blob)); // Create Worker instance using Blob
worker.onmessage = function(e) {
console.log('Result from worker:', e.data); // Output result returned by Worker
};
worker.postMessage({ a: 5, b: 3, operation: 'add' }); // Send data to Worker
Import scripts in ES module mode
new Worker('path/to/js', { type: 'module' });
Native APIs Available in Web Worker
Timers
: setTimeout and setIntervalNetwork Requests
: fetch, XMLHttpRequestWeb APIs
: WebSocket, FileReaderBinary Operations
: ArrayBuffer, BlobData Processing
: crypto, IndexedDB