What is a Web Worker?
while executing scripts in an HTML page, the page will become unresponsive until the script gets finished.
The table numbers specify the first browser version which fully support Web Workers.
HTML Web Workers Example
The example below will show you how to create a simple web worker which counts numbers in the background:
Check Web Worker Support
Before creation of a web worker, we need to check whether the user's browser is supporting it:
Create a Web Worker File
Here, we are creating a script which counts. The script will get stored in the "demo_workers.js" file:
The notable part of the code above is the postMessage() method - which posts a message back to the HTML page.
Note: Usually web workers are used for CPU intensive tasks and not for such simple tasks.
Create a Web Worker Object
Now we are having the web worker file which needs to be called from an HTML page.
The following lines are checking if the worker already exists, if not - it will create a new web worker object and will run the code in "demo_workers.js":
Throught the web workers we can be sending and receiveing messages .
Adding an "onmessage" event listener to the web worker.
When the web worker is posting a message, the code inside the event listener is executed. The data received from the web worker is stored in event.data.
Terminate a Web Worker
When a web worker object gets created, it will be working continously to listen for messages (even after the external script gets over) until the script gets terminated.
For terminating a web worker, and free browser/computer resources, use the terminate() method:
Reuse the Web Worker
If you are setting up the worker variable to be undefined, after it is terminated, you can reuse the code:
Full Web Worker Example Code
We have already looked into the Worker code in the .js file. Below is the code written for the HTML page:
Web Workers and the DOM