Web Workers in JavaScript
Add test marks in JavaScript with a Blob web worker and postMessage. Print the returned total, then terminate the worker; it cannot directly edit the page.
Run this example once in a fresh browser console. The console shows the printed results.
1const workerSource = `2self.onmessage = event => {3 const total = event.data.reduce((sum, value) => sum + value, 0);4 self.postMessage(total);5};`;6const url = URL.createObjectURL(new Blob([workerSource], { type: 'text/javascript' }));7const worker = new Worker(url);8worker.onmessage = event => {9 console.log('Marks total:', event.data);10 worker.terminate();11 URL.revokeObjectURL(url);12};13worker.onerror = event => {14 console.error('Worker failed:', event.message);15 worker.terminate();16 URL.revokeObjectURL(url);17};18worker.postMessage([18, 20, 17]);
Sample Output
Marks total: 55
The worker added 18, 20, and 17, then sent the result back. The page logs it later.
In this one
- Create a worker without a second file
- Send an array to a worker
- Receive a calculated result
- Release worker resources after use
How it works
- 1
Put the calculation inside workerSource.
- 2
Create a Blob URL and pass it to Worker.
- 3
Install success and error handlers before sending data.
- 4
Send the marks array using postMessage.
- 5
On reply, print 55, then stop the worker and release its temporary URL.
Edge cases
Worker blocked by page rules
A site may forbid blob worker addresses.
Try a local page with a suitable content security policy. Do not weaken a production site policy just to run a demo.
Stopped too early
terminate can cancel pending work.
Wait until onmessage has received the answer before stopping the one-use worker.
What's going on
A web worker is a script that runs separately from the page's main JavaScript work. It can calculate a result while the page stays free to respond to clicks. Here a worker adds three test marks and sends the total back.
Run this browser-only example in the console of a normal page that permits blob workers. A Blob holds the worker source as a small file in memory. createObjectURL gives that file a temporary address, so this example does not need a separate worker.js file.
postMessage sends the marks to the worker. The worker has its own onmessage function and answers through self.postMessage. The page prints the answer only after that message arrives. Terminating immediately after sending would be a mistake: the worker might stop before answering. Cleanup happens after success or failure. Workers cannot directly edit the page; send data back and let the page update itself.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Which method sends data?
Pick an answer to check it.
Question 2
When should this worker stop?
Pick an answer to check it.
Questions people ask
Can a worker change a paragraph?
Not directly. It has no document object. Send the result back to the page to update the paragraph.
Is a worker faster for three numbers?
Usually not. Starting it has a cost. Three marks keep the lesson small; larger calculations are a better reason to use one.
Why revoke the URL?
It releases the temporary file address after this worker is no longer needed.