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.
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.
- 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.html
that loads and runs amain
function frommain.js
. - Create a
main.js
file with amain
function that creates a worker from a file namedworker.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(...