What’s the big deal?
Enter web workers, which run in the background and communicate with the main thread via messages. With web workers, programs can delegate tasks such as processing large data troves while the main thread is free to process UI events , improving program efficiency and the overall user experience. For example, a worker could handle a large JSON file to mine relevant information to display in the UI.
Web Worker Applications:
- Reading/writing local storage databases
- Real time text formatting, spell checking, and syntax highlighting
- Filtering images in a canvas
- Processing large JSON datasets
- Processing multimedia (audio and video)
- Complicated math formulas, such as finding the largest prime number
Example: Filtering Images in a Canvas
As John Resig explains, “this demo makes use of Canvas to draw out a rendered scene…. when you turn on the workers, the scene is drawn in pieces. This is working by telling a worker to compute a slice of pixels. The worker responds with an array of colors to draw on the Canvas and the parent page changes the canvas.”
Workers are created and executed in one of the main program files with their code housed in a separate file. As demonstrated below, a worker is built using the
Worker constructor method, which takes a parameter of
.postMessage(), the parent thread can communicate messages to its workers.
.postMessage() is a cross-origin API the can transmit primitive data and JSON structures, but not functions.
The parent code may also have a callback function that listens for a response from the worker confirming its work is complete in order for it to enact another action. As in the example below, the callback function will contain a target, which identifies the worker (
'message') , and data, or the message posted by the worker.
Meanwhile, the worker, living in its own file, stands by with an
eventListener waiting to be called. When it receives the
message event from the parent code, it likewise communicates its response via the
A Note of Caution:
Since workers are resource intensive, it is good practice to terminate them once their jobs are complete. This can be accomplished either in the primary code :
Alternatively, the worker can terminate itself: