Efficient way to handle CPU-intensive tasks on ClientSide

2 mins read

Sometimes we have heavy CPU-intensive tasks to execute. Executing these tasks
on the browser’s main thread can lead to an unresponsive or frozen user interface.
We can follow several approaches to handle this situation.
First approach is to send the parameters to the server and execute the tasks
on it, and then retrieve the final results. However, this approach can be costly if
our server has limited resources or if our user base grows to a point where we
can no longer handle the load. This can also have impact on server
To address the limitations of the first approach, it’s recommended to execute
those CPU-intensive tasks on the client side without compromising user
experience. This can be achieved effectively through the use of Web Workers

What is WebWorker

It’s just a JavaScript script file that runs in the background, separate from the
main thread of the web application. This means we can perform heavy
calculations or other CPU-intensive tasks without causing your user interface to
freeze or become unresponsive.

– according to caniuse.com, its supported by 98.07% of user’s browser
Some key feature of Webworker

● Runs in a separate thread
● Communicate with the main thread

Some key feature of Webworker

● Runs in a separate thread
● Communicate with the main thread
● Can utilize multi-core CPUs
● No UI Blocking
Some Limitation of Webworker
● No Direct Access to DOM : Can not manipulate the dom directly from web
worker
● Limited Browser API and context : we can not access window object and
some browser api like localstorage from web worker
● Limited Communication: data exchanged must be serialized, as complex
objects or functions cannot be directly transferred

Type of Webworker

Dedicated workers
A Dedicated Web Worker is specific to the creating script (main thread) that
spawned it.

Shared Web Worker:
A Shared Web Worker is shared among multiple scripts running in different browsing
contexts (e.g., tabs, iframes). It allows collaboration and data sharing between these
scripts.

Conclusion
In conclusion, Web Workers offer a powerful tool for enhancing the
performance and responsiveness of your web applications. By carefully
considering their advantages and limitations, you can unlock their potential for
building a smooth, engaging, and resource-efficient user experience