Introducing Web Worker and how to use it
If you never heard about Web Worker, now is the chance to learn something new.
The browser by default uses a single thread. When you open web site, many tasks are starting like fetching API data, fetching image, onclick event and etc. So only one task can be executed at the time.
The browser is executing tasks concurrently, but not in parallel. To fix this issue we have to use Web Workers.
What is Web Worker?
Web Worker is a thread which is executing some code in parallel with the Main thread in the browser.
Example: You're fetching big posts data with image links in the data. One web worker can fetch the data, another can fetch the images and Main thread can render the data. This would be one of the best scenario. Although Web Workers have advantages, they have and disadvantages as well.
A Web Worker can’t directly manipulate the UI and has limited access to methods and properties of the window object. So if you need to manipulate with the UI, you have to return data to the Main thread.
Another thing is that they are expensive, so creating many workers is not the best idea. Use them properly.
How to use
Now I will explain how you can create Web worker in 3 ways
1. Separate File
2. Same File in string
3. Same File in a method
Terminating A Web Worker
By practice it's good to terminate a worker when it has served it's purpose. A worker can be terminated by calling the terminate() method on the main thread. This immediately terminates the worker regardless of whether or not it’s performing a task. A worker can also be terminated from within its scope. To do this, call the close() method from within the worker
Summary
In this post you learned how to run Web worker in 3 ways and how to fix performance issues. In next post I will implement real scenario for fetching thousands of images in worker and render in Main thread.
See you next time