Creating a Web Worker
Spawn a background thread for work.
Creating a Web Worker is a free JavaScript Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the JavaScript Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Why Web Workers?
JavaScript runs on a single main thread. A long calculation blocks everything: the UI freezes, clicks stop responding. Web Workers run scripts on a background thread, keeping the page responsive.
Creating a Worker
Spawn a worker by passing a script URL to the Worker constructor. The browser loads that file and runs it on a separate thread.
const worker = new Worker('worker.js');
// The code in worker.js now runs on its own thread.The Worker Script
The worker file is plain JavaScript but runs in its own global scope (no window, no document). It communicates only through messages.
// worker.js
console.log('worker started');
// This runs off the main thread.Two Separate Globals
The main page and the worker each have their own global scope and memory. They cannot share variables directly; they exchange copies of data via messages.
- Main thread:
window, DOM, UI - Worker thread:
self, computation, no DOM
Self in the Worker
Inside a worker, the global object is self (a DedicatedWorkerGlobalScope). You attach handlers and call APIs on it, though self is often implicit.
// worker.js
self.addEventListener('message', (e) => {
console.log('worker got:', e.data);
});Module Workers
You can create a worker that uses ES module import by passing the type: 'module' option. This lets the worker import other modules cleanly.
const worker = new Worker('worker.js', { type: 'module' });
// Inside worker.js you can now use import statements.Importing Scripts (Classic)
In a classic (non-module) worker, use importScripts to load extra scripts synchronously into the worker scope.
// Inside a classic worker:
importScripts('math-utils.js', 'helpers.js');
// Their globals are now available in the worker.Terminating a Worker
Stop a worker from the main thread with worker.terminate(), or from inside with self.close(). This frees the thread and its memory.
// From the main thread:
worker.terminate();
// From inside the worker:
// self.close();Handling Worker Errors
Listen for the error event on the worker to catch uncaught exceptions thrown inside it. The event carries the message, filename, and line number.
worker.addEventListener('error', (e) => {
console.log('worker error:', e.message, 'at line', e.lineno);
});Same-Origin Requirement
The worker script must be served from the same origin as the page (or via a Blob URL). You cannot load a worker directly from an arbitrary cross-origin URL.
// Same-origin file path - works:
const w1 = new Worker('/js/worker.js');
// You can also build one from a Blob URL when needed.Dedicated vs Shared
A Worker is dedicated: tied to the page that created it. A SharedWorker can be reached by multiple pages of the same origin. This course focuses on dedicated workers.
Quick Check
Test your understanding of creating Web Workers.
Recap
You learned to create Web Workers:
new Worker('worker.js')spawns a background thread.- The worker has its own global (
self) and no DOM. - Use
type: 'module'for imports, orimportScriptsin classic workers. terminate()/self.close()stop it.- Workers must be same-origin.
Next, messaging between threads.
Frequently asked questions
Is the “Creating a Web Worker” lesson free?
Yes — the full text of “Creating a Web Worker” is free to read here on the web, and the JavaScript Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the JavaScript Academy course, upgrade to CoddyKit PRO.
What will I learn in “Creating a Web Worker”?
Spawn a background thread for work. You practise JavaScript Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start JavaScript Academy?
No prior experience is required. JavaScript Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Creating a Web Worker” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this JavaScript Academy lesson?
Yes. Every JavaScript Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Creating a Web Worker
- Messaging with postMessage
- Transferable Objects
- Use Cases and Limitations