All You Wanted To Know About Web Workers in JavaScript

nirmal genji
4 min readNov 2, 2022

--

JavaScript Web Workers

What is a Web Worker

A web worker is simply a JavaScript process that runs in the background of a webpage, without affecting the performance of the page. The JavaScript by default is a single-threaded, managed by a single execution path known as Main Thread. This main thread is responsible for executing a code one line at a time. Whereas, a web worker is a separate JavaScript thread that allows you to execute multiple threads in parallel. It mainly can be created to offload the heavy computation work so that the main thread doesn’t get blocked.

The important difference between the main thread and a web worker is that web workers cannot perform DOM manipulation, only a main thread can do it Since web workers are in external files, they do not have access to the window, document or parent objects themselves. They do not execute in a global scope, having their own dedicated worker context known as ‘DedicatedWorkerGlobalScope.’

The most likely use cases of Web Workers

  • Pre-fetch and cache data for later use
  • Processing data for spell check, word count
  • Syntax highlighting, which you wouldn’t want to block code editing
  • Games, Image processing, Compression, etc.

Interacting with the Web Workers

The entry point of our web worker is onmessage() which is basically a listener, triggered by our application. The Worker() constructor creates a Worker object that executes the script at the specified URL. worker.postMessage() is to send the message to the worker and worker.onmessage = function(){…} to listen to the message from the worker. In addition, worker.onerror() fires when the error occurs and worker.terminate() immediately terminates the worker. Let’s understand this with React example - Computing Fibonacci of nth number.

To get started, create a new React app using CRA. Add worker.js to the app’s root directory or a public/ folder.

In src/App.js, add a function to run web worker. This will have the above-mentioned event listeners postMessage, onmessage, onerror, and terminate.

We will need a reducer file to maintain some state. Let’s put that in src/reducer.js.

Next, we will display computed Fibonacci results using the src/Results.js component.

Finally, Let’s put everything in src/App.js. This will have a useReducer, Input Field, Calculate button and a Result component.

NPM packages used
Ordinal - English ordinal for numbers.
React-spinners - Loading Bar spinner.

Tadah.🎉 That’s it. This way, you can interact with UI even if the blocker code is running. Now, let’s see how web workers helped us to overcome the problem of blocking long-running computation. Each time we click on Calculate, the job of computing FN is delegated to a web worker. Notice that we have added the calculateFib function inside the worker file. This way, your UI stays responsive no matter what time it takes for the previous input number. Without this, if you add a big number to compute the Fibonacci, it will block UI interaction.

Result

Observe the computation with the help of worker for 45
Here is result

Browser Support

The web worker support for various browsers can be checked on Caniuse.com. It has global support of more than 98%.

Browser Support

Web Workers vs Service Workers

Service workers are a type of worker that acts as a proxy between the Browser and a network/cache. Like web workers, they are registered in the main JavaScript file itself. Being proxies, service workers can intercept the requests made by the document, making them provide offline access as well as improve the web page performance. This is just a surface scratching for the Service worker, as it has its own way of registering into the main JavaScript file, a lifecycle of its own, and real-world use cases. Below are the links to know more about it.

https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API https://developer.chrome.com/docs/workbox/service-worker-overview/

The Takeaway

Web workers are undoubtedly the coolest new features in modern web browsers. You can use the web workers to run the JavaScript off the browser’s main thread in case of heavy computations.

--

--