Performing work on separate threads with Web Workers
Web Workers allow browser operations to take place outside the main thread. Once created, communication between threads is made by passing messages. In this recipe, we'll see how to create a very simple worker, and send it a message from the main thread.
Getting ready
This recipe assumes that you already have a workspace that allows you to create and run ES modules in your browser. If you don't, please see the first two chapters.
How to do it...
- Open your command-line application and navigate to your workspace.
- Â Create a new folder named
05-01-performing-work-with-web-workers. - Copy or create an
index.htmlthat loads and runs amainfunction frommain.js. - Create a
main.jsfile with amainfunction that creates a worker from a file namedÂworker.js. Then post a message of typehello-message to theworker:
// main.js
export function main() {
console.log('Hello, from main.');
const worker = new Worker('./worker.js');
worker.postMessage(...