Web Workers flashcards
Run heavy JavaScript off the main thread.
Beginner friendly, starts from zero
0
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. Start from zero (12 cards): What a worker is, the words you need, and your first worker.
- 2. Core basics (15 cards): Why the page freezes, how to move work to a worker, and how messages flow both ways.
- 3. Next steps (15 cards): Transfers, request ids, Comlink, bundlers, pools, OffscreenCanvas and cancellation.
- 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
documentis 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
importcode 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 workerworker.postMessage(msg)Send a structured-clone copyworker.postMessage(msg, [buf])Send and transfer ownershipworker.addEventListener("message", fn)Receive repliesworker.addEventListener("error", fn)Uncaught errors and load failuresworker.terminate()Stop immediatelycanvas.transferControlToOffscreen()Give drawing to a worker
Worker side
self.onmessage = ({ data }) => {}Receive workself.postMessage(result, [result.buffer])Reply and transferself.close()End this workerimport { x } from "./m.js"Module worker importsimportScripts("/lib.js")Classic worker onlyself.crossOriginIsolatedShared memory allowed?/// <reference lib="webworker" />TypeScript worker types
Shared memory
new SharedArrayBuffer(bytes)Memory shared across threadsAtomics.add(view, i, n)Atomic incrementAtomics.compareExchange(view, i, old, next)Lock-free updateAtomics.wait(view, i, value)Sleep (workers only)Atomics.waitAsync(view, i, value)Promise-based waitAtomics.notify(view, i, count)Wake waiting threads
Isolation headers
Cross-Origin-Opener-Policy: same-originSeparate browsing context groupCross-Origin-Embedder-Policy: require-corpEmbeds must opt inCross-Origin-Embedder-Policy: credentiallessLoad embeds without cookiesCross-Origin-Resource-Policy: cross-originLet isolated pages embed this file
Which background tool
Dedicated WorkerCPU work for one pageSharedWorkerOne worker for all same-origin tabsService WorkerNetwork proxy, offline, pushAudioWorkletReal-time audio processingMessageChannelDirect port pair between contextsBroadcastChannelSimple pub-sub across tabs