Skip to article content
FrontendXLesson 26 / 30

Web Workers and Main-Thread Offloading

Build a precise mental model of JavaScript values, scope, functions, objects, arrays and asynchronous behavior, then implement and debug real utilities from first principles instead of memorizing outputs.

advanced · about 40 minutes · 6 exercises

  • Predict
  • Explain
  • Implement
  • Debug
  • Test
  • Interview

What you will be able to do

#
  • Move CPU-heavy work off the main thread with a Worker.
  • Send data with postMessage and reason about structured clone.
  • Distinguish a dedicated worker from a service worker.

Overview

#

Why offload

JavaScript runs on a single main thread that also handles rendering and input. A long synchronous loop blocks that thread, so the page freezes. A Web Worker runs a separate script on another thread, so the main thread stays responsive while heavy work proceeds.

snippet.js
// worker.js
self.onmessage = (event) => {
  const result = event.data.numbers.reduce((a, b) => a + b, 0);
  self.postMessage(result);
};

// main.js
const worker = new Worker('worker.js');
worker.onmessage = (event) => console.log(event.data);
worker.postMessage({ numbers: [1, 2, 3] });

Messaging and cloning

postMessage sends a copy of the data using structured clone, which supports objects, arrays, Map, Set and ArrayBuffer but not functions or DOM nodes. Transferable objects such as an ArrayBuffer can be moved instead of copied, which avoids a large copy at the cost of losing access on the sending side.

Worker types

A dedicated worker belongs to one page. A shared worker is reachable from several pages of the same origin. A service worker is different: it is an event-driven proxy for network requests that enables offline caching and push, and it does not run your computation on demand. Workers have no DOM access, so all rendering stays on the main thread.

Exercises

#

Reference answers and expected output are authored, not executed in this browser. Nothing you type is run, and there is no Run or Pass control on this page.

  1. Exercise 1Predict

    What happens when you postMessage a function to a worker?

    Read the code, then choose the best answer. The reference explanation stays hidden until you respond.
    stimulus.javascript
    worker.postMessage({ run: () => 1 });
    Choose the best answer
  2. Exercise 2Explain

    Explain the difference between a Web Worker and a service worker.

    starter.text
    const worker = new Worker('compute.js');

    Reveal the reference answer
    reference.text
    A Web Worker runs a script on a background thread to keep the main thread free, and it communicates with the page through postMessage. A service worker is a special worker that sits between the page and the network as a programmable proxy, so it can intercept fetches, serve cached responses and handle push and background sync. A service worker does not run a computation on demand the way a dedicated worker does.

    Authored expected output: one offloads work, the other proxies network requests

    The answer should separate on-demand computation from network interception and offline behavior.

  3. Exercise 3Implement

    Implement a main-thread helper `runInWorker(worker, payload)` that posts payload and resolves with the worker's reply.

    starter.javascript
    function runInWorker(worker, payload) {
      // your code here
    }

    Reveal the reference answer
    reference.javascript
    function runInWorker(worker, payload) {
      return new Promise((resolve) => {
        worker.onmessage = (event) => resolve(event.data);
        worker.postMessage(payload);
      });
    }

    Authored expected output: a promise that resolves with the worker result

    Wrapping the message round trip in a promise lets the caller await the result. The onmessage handler resolves with the data the worker posts back.

  4. Exercise 4Debug

    This worker is meant to receive a DOM element but throws. Explain the cause and the fix.

    starter.javascript
    const el = document.querySelector('#chart');
    worker.postMessage(el);

    Reveal the reference answer
    reference.javascript
    A DOM node is not structured-cloneable, so postMessage throws a DataCloneError. A worker also has no DOM, so it could not use the node anyway. The fix is to extract the plain data the worker needs, such as numbers or strings, and send that, then let the main thread apply the result to the DOM.

    Authored expected output: DataCloneError

    The answer should name structured clone limits and the architectural reason a worker cannot touch the DOM.

  5. Exercise 5Test

    Write assertions that prove structured clone copies a Map and that a transferred ArrayBuffer is detached on the sender.

    starter.javascript
    function assertEqual(actual, expected, label) {
      if (actual !== expected) throw new Error(label + ': expected ' + expected + ' but got ' + actual);
    }

    Reveal the reference answer
    reference.javascript
    const source = new Map([['a', 1]]);
    const cloned = structuredClone(source);
    cloned.set('b', 2);
    assertEqual(source.size, 1, 'the clone is independent');
    assertEqual(cloned.size, 2, 'the clone has the new entry');
    const buffer = new ArrayBuffer(8);
    assertEqual(buffer.byteLength, 8, 'buffer starts with a length');
    structuredClone(buffer, { transfer: [buffer] });
    assertEqual(buffer.byteLength, 0, 'transferred buffer is detached');
    console.log('all assertions passed');

    Authored expected output: all assertions passed

    structuredClone copies a Map into an independent value. Transferring an ArrayBuffer moves it, so the original becomes detached with a byteLength of zero.

  6. Exercise 6Interview

    How would you keep a page responsive while processing a large file the user uploads?

    Reveal the reference answer
    reference.text
    I read the file in chunks and hand the parsing to a Web Worker so the main thread stays free to render progress and accept input. I send ArrayBuffers as transferables to avoid copying, stream partial results back with postMessage, and show progress from those messages. If the work is a network proxy or offline concern rather than computation, I use a service worker instead.

    The answer should name chunking, a worker for heavy parsing, transferables to avoid copies and progress messaging.

Common misconceptions

#
  • A Web Worker can access the DOM directly.
  • postMessage passes a reference rather than a copy.
  • A service worker is just a background Web Worker.

Follow-up practice

#
  • javascript-foundations-performance-and-memory
  • javascript-foundations-async-patterns

Related resources

#

Your progress

#

Answers, drafts and completion marks are stored only in this browser. Nothing is sent to a server and no account is used.

Verification: authored. Answers and outputs on this page are authored reference material, not executed results.

© 2026 FrontendX. All rights reserved.