HTML5 Web Workers
What is Web Worker?
Everyone wants a website or application which work fast and can execute multiple operations simultaneously without affecting the performance of the page. However, sometimes we experience some delay response or degraded performance of page while executing some large operations. So this problem can be solved using the Web Workers.
Following are some key features of the Web Workers:
Types of Web Workers:
In HTML5 Web Workers are of two types:
The dedicated worker can be accessed by only one script which has called it. The dedicated worker thread end as its parent thread ends. Dedicated workers are only used by one or single main thread.
It can be shared by multiple scripts and can communicate using the port. Shared workers can be accessed by different windows, iframes or workers.
Note: In this section, we will use dedicated Web Workers.
Web Workers Browser Support:
Before learning the web Workers first, we need to check about the browser support. So following is the code which checks whether your browser is supporting or not.
ExampleTest it Now
Creation of Web worker file:
Here we have created a web worker file for calculating the square of the number. And saved it with the name "worker.js".
Below is the code for worker.js file.
Creating the Web Worker Object:
In above "worker.js" file, we have created the JS file for web Worker now it needs to call on an HTML file. To create the web worker object, you need to call the Worker() constructor.
Following is the syntax to call and create the object of Web Worker:
Sending messages between the Worker thread and main thread:
All the communication of Worker thread depends on the postMessage() method and onmessage event handler.
Terminating the Web Worker:
If you want to immediately terminate the currently running worker in the main thread, then you can terminate it by calling the terminate() method of Web Worker. Here is the syntax for web worker termination:
Web Worker can be terminate in worker thread also by calling the close() method.
ExampleTest it Now
In the above example in HTML file we have used