Hello World Master

Tutorials, articles and quizzes on Software Development

Javascript > Articles

How to create a Web worker

This article is associated with the following course
Introduction to Web Workers

To start, create a webpage using web workers, the first thing we want to do is create a small webpage containing an HTML file and two Javascript files.

The first Javascript file should be named script.js and the second file should be named worker.js

The HTML file should contain the following markup

<div id="container"></div>
<script src="./script.js"></script>

In your script.js file, initialize a worker instance that takes in the location of the script we want to run inside a Web Worker.

const myWorker = new Worker('worker.js');

Next, we want to go to our worker.js file and add some code that will run on the main thread. I am going to just add a variable.

const a = 2;

Use postmessage to send data from the Webworker back to the main thread

Now that we have declared our variable inside our Web Worker, we want to send the data (our variable) inside it back to the main thread

const a = 2;


We now need to add the handler that will run when postmessage is called. To do this, we need to set the onmessage property of our worker to a function that can be used to get back the data passed in the postMessage parameter in our Web worker.

Go back to the script.js file and set the onmessage attribute to be the following function here

myWorker.onmessage = function(e) {

To get the data from our Web Worker we would call e.data. Lets set the HTML of our container div element to be the value from the variable inside our Web Worker

myWorker.onmessage = function(e) {
  document.getElementById('container').innerHTML = e.data;