Utilizing Web Worker for Heavy Lifting Tasks

Mon, January 27, 2025

utilizing-web-worker-for-heavy-lifting-tasks

As web developers, one of our key responsibilities is ensuring the web applications we build run exceptionally well and deliver high performance, because user time and experience are paramount.

Challenges for web developers will start to occur when we have a feature that requires a long processing time, for example: managing very large data (import/export excel which contains transformation, validation, etc.), image and video processing (compression, filter application, object recognition using Machine Learning), etc. So that our website can still be used while the process is ongoing, we need to run the process in the background, for that let's get to know Web Workers.

Introduction

Web Worker is a Web API we can use to run scripts in the background, executing them in a thread separate from the main application thread.

Since processes run independently, worker threads and main threads won't interfere with each other. We can leverage web workers to run heavy, time-consuming tasks in the background, allowing users to continue using our web application normally without waiting for lengthy processes to complete.

Usage

We can use Web Workers by initializing a Worker, , where worker.js contains the code to be executed in the worker thread. We can perform almost anything in web workers, except directly manipulating the DOM and accessing window objects, since workers run in a different global context (WorkerGlobalScope). Instead, we can use self. A list of supported functions and Web APIs can be checked in the supported functions and supported Web APIs.

As discussed in the previous paragraph, worker threads and main threads run independently, so how do they interact? They exchange messages using the function to send messages and to receive messages.

Implementation

Let's try with a simple example first to understand the concept, here is the attached code index.html and worker.js.

The result is as shown in the image below, when the "Start Heavy Task" button is clicked, the Web worker starts working on its task, first, next to the button a text will appear that says "Starting the heavy task...", then 3 seconds later the text will change to "Task finished".

Screenshot 2025-01-27 at 09.25.48.png

Let's try a more "real" implementation, I use React, Web Worker and Zustand. I use Zustand to run the Worker (initiation, sending and receiving messages, downloading csv and displaying notifications to the User), I do everything in the store so we can trigger the worker and receive notifications on any page. Here is the code attachment. Full Code

The result is like the video below, as we can see, I am free to move from page to page or do anything while the Export CSV process is running, because the process is running in the background.

A good User Experience isn't it? hope it is useful.