Setting up a dedicated worker

Calling a new Worker() with a filename in the constructor argument is all you need to do to spawn a dedicated worker:

// script.js loaded on index.htmlconst awesomeWorker = new Worker('myworker.js');

Using the new Worker constructor, we created a Worker instance. This will make the browser download the myworker.js file and start a new OS thread for it.

This is what we can place in the myworker.js file:

// myworker.jsconsole.log('Hello world!');

This logs Hello world inside the console.

A worker can create a sub-worker itself, and everything below will apply to that, as well.

Get Learn ECMAScript - Second Edition 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.