Suggest an editImprove this articleRefine the answer for “What does a Web Worker do?”. Your changes go to moderation before they’re published.Approval requiredContentWhat you’re changing🇺🇸EN🇺🇦UAPreviewTitle (EN)Short answer (EN)A **Web Worker** is a separate thread for running JavaScript code that works in parallel with the main thread (the UI thread). **Key point:** it does not block the interface and can run heavy computations, then pass the result back to the main thread.Shown above the full answer for quick recall.Answer (EN)Image## What a Web Worker is > A **Web Worker** is a separate thread for running JavaScript code, > working **in parallel with the main thread (the UI thread)**. It **does not block the interface** and can run heavy computations, then pass the result back to the main thread. ## The problem without a Web Worker JavaScript in the browser is **single-threaded** - everything runs in one thread: - page rendering - event handling - running your code If you run a heavy loop in that thread: ```javascript for (let i = 0; i < 1e9; i++) {} console.log('Done!'); ``` the page will "freeze" - the interface stops responding until the loop finishes, because the **Event Loop** is busy. ## The solution - a Web Worker With a Web Worker you can move that computation **into a separate thread**: ```javascript // main.js const worker = new Worker('worker.js'); worker.postMessage(1e9); // send the task worker.onmessage = (event) => { console.log('Result:', event.data); }; ``` ```javascript // worker.js onmessage = (event) => { let sum = 0; for (let i = 0; i < event.data; i++) sum += i; postMessage(sum); // send the result back }; ``` Now the heavy computation runs **in the background**, and the UI stays responsive. ## How it works under the hood 1. The main thread creates a worker via `new Worker('script.js')`. 2. The browser starts a **separate JS thread**. 3. Communication between threads happens through **messages** (message passing). 4. The transfer is **asynchronous**, data is serialized (structured clone). 5. The worker does not have access to the DOM, `window`, or `document`. ## Exchanging data (message passing) Communication happens through the `postMessage` and `onmessage` events: ```javascript // main.js worker.postMessage({ action: 'sum', a: 5, b: 7 }); // worker.js onmessage = (e) => { if (e.data.action === 'sum') { postMessage(e.data.a + e.data.b); } }; ``` You can pass: - strings, numbers, objects - `ArrayBuffer`, `Blob`, `File`, `ImageBitmap` - even **Transferable objects**, to pass data without copying it ## One-sided limitations A Web Worker is **isolated**: - no access to `document`, `window`, `alert()`, `localStorage` - has access to: `fetch`, `XMLHttpRequest`, `WebSocket`, `setTimeout`, `indexedDB`, `crypto`, etc. ## Types of Web Workers | Type | Where it is used | Features | | --- | --- | --- | | **Dedicated Worker** | One per one | Works only with the script that created it | | **Shared Worker** | Several tabs/scripts | One worker for all pages (by origin + URL) | | **Service Worker** | Between the browser and the network | Caches requests, works even offline | ## Shared Worker example ```javascript // shared-worker.js onconnect = (event) => { const port = event.ports[0]; port.onmessage = (e) => { port.postMessage(`Received: ${e.data}`); }; }; ``` Several tabs can connect to the same Shared Worker - for example, to exchange data between tabs. ## Service Worker (a special type) > A Service Worker is not just a thread, it's a "proxy" between the browser and the network. It intercepts HTTP requests, caches responses, and lets an app work **offline**. (Example: PWA apps, push notifications, background sync.) ## Service Worker example ```javascript // service-worker.js self.addEventListener('fetch', (event) => { event.respondWith( caches.match(event.request).then((cached) => { return cached || fetch(event.request); }) ); }); ``` This means: if there is a cached response, return it, otherwise load it from the network and save it. ## Streaming data processing in a worker A worker can use the Streams and Fetch APIs: ```javascript onmessage = async (e) => { const response = await fetch(e.data.url); const text = await response.text(); postMessage(text.length); }; ``` This way you can process network data in the background, without blocking the UI at all. ## "Parallel" computation example ```javascript const workers = Array.from({ length: 4 }, () => new Worker('calc.js')); let completed = 0; let result = 0; workers.forEach((w, i) => { w.postMessage(i); w.onmessage = (e) => { result += e.data; if (++completed === 4) console.log('Done:', result); }; }); ``` This way computation can be distributed across several threads ("pseudo-parallelism"). ## When to use Web Workers | Scenario | Why it's useful | | --- | --- | | Complex computations | JSON parsing, cryptography, machine learning | | Processing large data | filtering/aggregating arrays, processing CSV | | Working with images | compression, filters, thumbnail generation | | Games / animation | physics calculations without interface lag | | WebSocket + data analysis | streaming processing | ## A simple analogy > Imagine the browser is a kitchen. > > - The main thread (the main JS) is the chef who cooks the dish and serves the guests. > - The Web Worker is an assistant at another station who chops vegetables. > > The chef gives a task -> the assistant does it in the background -> returns the result. > No one gets in anyone's way. ## Summary | Component | What it does | | --- | --- | | **Web Worker** | A separate thread for running code | | **Main advantage** | Does not block the UI | | **Data exchange** | Through `postMessage` / `onmessage` | | **Limitations** | No access to the DOM, `window`, `document` | | **Types** | Dedicated, Shared, Service Worker | | **Main uses** | Background computation, caching, offline mode, synchronization |For the reviewerNote to the moderator (optional)Visible only to the moderator. Helps review go faster.