Creating a worker
Learn to create a worker with the Worker constructor and bind its script.
The Worker constructor
You create a worker with new Worker(url). The url is the path to a separate JavaScript file that holds the code running in the worker thread.
const worker = new Worker('sorter.js');The call returns a Worker instance. You send messages to it, listen for messages and, when done, close it with terminate(). You can start several workers on the same page; each runs in its own thread.
Dedicated worker and its file
A worker started with new Worker() is called a dedicated worker: it is bound only to the page that created it. When the page closes, the worker ends too.
The worker file is a regular JavaScript file loaded separately from the main thread. The browser fetches it following the same-origin policy. Loading a worker from another origin requires importScripts or CORS headers.
Exercise Start and close the sorter worker
Assign a new Worker from 'sorter.js' to a worker variable. Then close it with worker.terminate().
Show example solution
const worker = new Worker('sorter.js');
worker.terminate();
Test yourself
-
Close the worker
worker.____();Show answer
worker.terminate(); -
Which statement is true about the worker file?
- It can access the DOM directly
- It can read variables from the main thread
- It is loaded following the same-origin policy
- It can contain HTML
Show answer
It is loaded following the same-origin policy — Correct! The worker file is a regular JS file bound by the same-origin policy.
-
Worker constructor parts
- new Worker(url)
- creates a worker
- terminate()
- closes the worker
- sorter.js
- worker file
- dedicated worker
- page-bound