Workers run JavaScript off the main thread via message passing—ideal for CPU-heavy tasks.
Types
- Dedicated workers tied to a creator script.
- Shared workers (limited support).
- Service workers for network interception (different lifecycle).
Constraints
- No DOM access—exchange structured clones with main thread.
- Transferables avoid copying large buffers.
Use cases
Parsing large CSVs, cryptography (WebCrypto + worker), wasm compute modules.
Operational complexity
- Worker bundling + import maps differ per toolchain—document how relative paths resolve.
- Service workers are not generic workers—lifecycle mistakes ship stale caches.
Starter files
// main.js
const w = new Worker('/workers/parse.js', { type: 'module' });
w.postMessage({ csvText: payload });
w.onmessage = (e) => renderRows(e.data.rows);
// workers/parse.js
self.onmessage = (evt) => {
const rows = evt.data.csvText.split(/\n/).map((l) => l.split(','));
self.postMessage({ rows });
};
Important interview questions and answers
- Q: What does progressive enhancement mean in API-driven pages?
A: Core tasks should work with baseline HTML first, then richer APIs enhance experience when supported. - Q: Why is feature detection better than browser sniffing?
A: It checks actual capability, avoids brittle UA assumptions, and degrades gracefully. - Q: What is the first accessibility check before shipping any page?
A: Verify keyboard-only task completion with visible focus and meaningful accessible names.
Tip: Workers cannot touch the DOM—use postMessage to coordinate.