Web Workers

Web workers are part of the living standard widely known as HTML5. To create one, you call the global Worker constructor with the URL of a script.

​ 
​var​ worker = ​new​ Worker(​'worker.js'​);
​ 
worker.addEventListener(​'message'​, ​function​(e) {
​ 
console.log(e.data); ​// echo whatever was sent by postMessage​
​ 
});

(Usually, we want only the data property from the message event. If we were binding the same event handler to multiple workers, we could use e.target to determine which worker emitted the event.)

So, now we know how to listen to workers. Conveniently, the interface for talking to workers is symmetrical: we use worker.postMessage to send it, and the worker uses self.addEventListener(’message’, ...

Get Async JavaScript now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.