HTML5 Web Workers
What is a Web Worker?
When a script is executed in an HTML page, the state of the page is unresponsive until the script is complete.
Web workers are supported in Internet Explorer 10, Firefox, Chrome, Safari and Opera.
HTML5 Web Workers instance
The following example creates a simple web worker that counts in the background:
Run the program and try it out
Demo_workers.js file code:
Check if the browser supports Web Worker
Before creating a web worker, check if the user's browser supports it:
// Web worker support!
// Related code.....
// Sorry! Web Worker..
Create a web worker file
Here we have created a counting script. The script is stored in the "demo_workers.js" file:
The important part of the above code is the postMessage() method - it is used to return a message to an HTML page.
Note : Web workers are typically not used for such simple scripts, but for tasks that are more CPU intensive.
Create a Web Worker object
We already have a web worker file, now we need to call it from the HTML page. /p>
The following code checks for the existence of a worker. If it doesn't exist, it creates a new web worker object and then runs the code in "demo_workers.js": /p>
Then we can get and receive messages from the web worker.
Add an "onmessage" event listener to the web worker:
<p When web="" worker="" passes a message, the code in the event listener is executed. There is data from="" event.data="" in event.data="".
Terminate Web Worker
When we create a web worker object, it continues to listen for messages (even after the external script completes) until it is terminated.
To terminate the web worker and release the browser/computer resource, use the terminate() method:
Complete web worker instance code
We have seen the Worker code in the .js file. Here is the code for the HTML page: