Web workers and message passing
A web worker can do background computation so the page remains responsive.
How it works
Send the worker the input needed for one calculation, then let the page continue receiving clicks and drawing updates. Keep DOM changes in the callback on the page. As an example, a worker can count the words in a long document and send only the total back, keeping the rendering step small.
Walk through an example
The page starts a worker and sends input with postMessage. The worker computes a result and sends it back. The page receives a message and updates the DOM itself.
What to watch for
Ordinary worker scripts do not access the page’s DOM. Large transfers can be expensive, so measure before splitting small tasks into worker messages.
Check your understanding
Which side should update the heading with the total?
See the example and explanation
- Worked example
- Given
A worker finishes counting words. - Answer
The page’s main script.
The worker sends the count in a message. The page owns the DOM and can use the message to update it.