So what are Web Workers?
A web worker is a JavaScript program running on a different thread, in parallel with main thread.
[…]
A main thread can ‘kill’ web workers which it spawned, and a web worker can ‘kill’ itself. When a web worker dies, threads attached to it die as well.
[…]
Most importantly, web workers should be used in following cases
[…]
Enough talking, let’s get into the code and implement our first web worker.
[…]
In above code, we are creating a web worker from file worker.js.
[…]
So far we have understood how to deal with web workers. Now let’s have a look at how web workers works in practice. Below is a very simple example of web worker.
We will get down to implementation of for loop inside web worker soon but it’s very useful to break down working on web workers step by step, which will help us clear many concepts related to web workers.
[…]
We can see that while web worker was executing for loop, our page or tab did not freeze at all. Hence we proved that web workers are non-blocking.
[…]
As we talked earlier, a web worker has ability to spawn other web workers and communicating with them. This follows same principles like spawning web workers from main thread. Whenever you want to create new child web workers from a parent web worker, imagine you are inside main thread and apply same principles.
We can import any external JavaScript inside web worker using importScript function using importScript(file.js, [...files]). This function is available in global context of web worker hence you can use self as well to access it.
[…]