The simplest possible definition of a webworker that I can think of will be:
A piece of code/functionality that offloads tasks from the main thread of JavaScript and runs in in another thread parallelly so that the main thread remains free"
Now, the question here arises, why do we want to offload tasks? We want to offload tasks because JavaScript is a single threaded language and if we have a task which is computationally expensive, until it finishes executing, it will not let all the subsequent tasks after it to run, thereby affecting the user experience.
To give an example, suppose we have two buttons where one calculates the sum and the other changes the color of the browser window. Now, if we just click on the button to "change color", it will work perfectly but if we click on the button to "calculate sum", and if that calculation is computationally expensive, then our change color button becomes unresponsive and we are not able to change the color of our browser window until the sum calculation is completed!
Below is an example demonstrating the same:
So, the above demonstrated problem can be easily solver using a web worker!!
To make a webworker, we first make a new worker.js file and then in our main.JS file, we call the Worker() constructor, and pass the URL of the worker.JS file in it.
Now, we want to both the main and the worker script to communicate and pass data between them. For that we have different methods provided by the Worker constructor.
Two of the prominent one's are:
- postMessage()
- onmessage
postMessage() helps in sending data from the main.js file to the worker.js file and vice versa. In the next screenshot, we can see we are passing the string "hello from the main worker" from the main.js file to the worker file and then the worker file is consoling it
onmessage is an event listener that helps in monitoring whether there are any messages coming in from the main or the worker thread and if so, it does the appropriate steps of what it is instructed to do. In the below screenshot, we can see the onmessage eventlistener in the worker file which consoles the "hello from the main worker" message coming in from the main thread.
Now, for the final piece! We will try to solve our initial problem of not being able to change color for a while when we clicked on the calculate sum button by using a webworker!
Here's the final result:
Now, that we have covered how can we implement a webworker, lets cover some use cases:
- For fetching large amounts of data
- Parsing a large file
- Computationally expensive functionality
Also, one thing to note is that webworkers doesn't have access to the following browser objects:
- The window object
- The document object
- The parent object
That's all folks! Thank you for reading!
Resources and references: