TodayTools

Web Workers flashcards

Run heavy JavaScript off the main thread.

Donate
Beginner friendly, starts from zero
Section
How to study
0
Web WorkersStart from zero · 1 of 12

What is a Web , in one plain sentence?

A Web is a helper the browser gives a web page, so some of its JavaScript can run in the background and slow jobs do not freeze the page.

A helper in the back room.

All topics

Web Workers at a glance

A Web Worker lets a web page run slow JavaScript in the background, so the page never freezes.

Like a cafe hiring a cook, so the waiter can keep serving while big orders are cooked; they pass notes through a hatch.

Words you will meet

Thread
One line of work a computer runs step by step
Main thread
The page's own line that runs code and draws the screen
Worker
A background helper with its own thread
Task
One chunk of work the browser does
DOM
The browser's live tree of everything on the page
Message
A copy of data sent between page and worker
Listener
A function that runs when a message arrives

The steps

  1. 1. Start from zero (12 cards): What a worker is, the words you need, and your first worker.
  2. 2. Core basics (15 cards): Why the page freezes, how to move work to a worker, and how messages flow both ways.
  3. 3. Next steps (15 cards): Transfers, request ids, Comlink, bundlers, pools, OffscreenCanvas and cancellation.
  4. 4. Go deeper (15 cards): Shared memory, Atomics, cross-origin isolation, WebAssembly threads, worklets and real-world performance.
All 12 cards in Start from zero
What is a Web Worker, in one plain sentence?
A Web Worker is a helper the browser gives a web page, so some of its JavaScript can run in the background and slow jobs do not freeze the page.
Before workers, what happened when a page had a big job to do?
Everything ran on one line of work. Opening a huge file froze buttons, typing and scrolling until it finished, and the browser sometimes showed 'page not responding'.
Where might you already meet Web Workers in daily life?
Photo editors in the browser applying filters, online spreadsheets working out formulas, maps drawing as you drag, and video calls blurring your background can all use workers to stay smooth.
What everyday picture fits a Web Worker best?
A small cafe with one waiter who also cooks: while he cooks a big order, nobody gets served. A worker is a cook in the kitchen; the waiter keeps serving, and they pass notes through a hatch.
What do 'thread' and 'main thread' mean?
A thread is one line of work a computer runs, step by step. The main thread is the page's own line: it runs your JavaScript and also draws the screen and handles clicks.
What do 'task', 'layout' and 'paint' mean?
A task is one chunk of work the browser does, like running a click handler. Layout is working out where each thing goes; paint is drawing the pixels. Screens redraw about every 16 ms, so long tasks cause stutter.
What is the 'DOM', and why does it matter here?
The DOM is the browser's live tree of everything on the page, and document is how JavaScript reaches it. Workers cannot touch it; only the main thread can change what is on screen.
What do 'message', 'event' and 'listener' mean?
The page and the worker do not share variables, so they send messages, which are copies of data. When a message arrives, an event fires, and a listener, a function you set up earlier, runs with that data.
What do 'module', 'import' and 'URL' mean?
A module is a JavaScript file that can import code from other files. A URL is a web address, like /js/csv-worker.js, which tells the browser where the worker's own file lives.
What do you need before starting this topic?
A modern browser and a text editor; nothing to install. Workers must load from a web address, not a double-clicked file, so run a tiny local server (a program that shares a folder), which many editors offer. Basic JavaScript helps.
Your first tiny win: what does this page print?
The page starts a worker, sets a listener, and sends it 5. The worker squares it and posts back, so the listener prints 25.
What will you be able to do after this topic?
Move heavy jobs like file parsing off the main thread, send data back and forth safely, handle errors and stop workers, and judge when a worker is worth it.
Web Workers cheatsheet

Page side

  • new Worker(new URL("./w.js", import.meta.url), { type: "module" }) Create a bundler-friendly module worker
  • worker.postMessage(msg) Send a structured-clone copy
  • worker.postMessage(msg, [buf]) Send and transfer ownership
  • worker.addEventListener("message", fn) Receive replies
  • worker.addEventListener("error", fn) Uncaught errors and load failures
  • worker.terminate() Stop immediately
  • canvas.transferControlToOffscreen() Give drawing to a worker

Worker side

  • self.onmessage = ({ data }) => {} Receive work
  • self.postMessage(result, [result.buffer]) Reply and transfer
  • self.close() End this worker
  • import { x } from "./m.js" Module worker imports
  • importScripts("/lib.js") Classic worker only
  • self.crossOriginIsolated Shared memory allowed?
  • /// <reference lib="webworker" /> TypeScript worker types

Shared memory

  • new SharedArrayBuffer(bytes) Memory shared across threads
  • Atomics.add(view, i, n) Atomic increment
  • Atomics.compareExchange(view, i, old, next) Lock-free update
  • Atomics.wait(view, i, value) Sleep (workers only)
  • Atomics.waitAsync(view, i, value) Promise-based wait
  • Atomics.notify(view, i, count) Wake waiting threads

Isolation headers

  • Cross-Origin-Opener-Policy: same-origin Separate browsing context group
  • Cross-Origin-Embedder-Policy: require-corp Embeds must opt in
  • Cross-Origin-Embedder-Policy: credentialless Load embeds without cookies
  • Cross-Origin-Resource-Policy: cross-origin Let isolated pages embed this file

Which background tool

  • Dedicated Worker CPU work for one page
  • SharedWorker One worker for all same-origin tabs
  • Service Worker Network proxy, offline, push
  • AudioWorklet Real-time audio processing
  • MessageChannel Direct port pair between contexts
  • BroadcastChannel Simple pub-sub across tabs
Donate