Posts in current category
May 03, 2021 13:10 HTML5
When a script is executed in an HTML page, the state of the page is non-responsive until the script is complete.
Internet Explorer 10, Firefox, Chrome, Safari and Opera all support Web workers.
The following example creates a simple web worker that counts in the background:
demo_workers.js file code:
Before you create a web worker, check to see if the user's browser supports it:
This step of detection is very important! You must detect before you can guarantee that the web worker will operate smoothly next!
Here, we create a counting script. The script is stored in demo_workers.js File:
An important part of the above code is the postMessage() method - which is used to send back a message to an HTML page.
Note: Web workers are typically not used for such simple scripts, but for tasks that consume more CPU resources.
We already have a web worker file, and now we need to call it from the HTML page. / p>
The following code detects the presence of a worker, if it does not exist, - it creates a new web worker object and then runs the code in "demo_workers.js": /p
Then we can send and receive messages from the web worker.
Add a "onmessage" event listener to the web worker:
When a web worker delivers a message, the code in the event listener is executed. T here is data from event.data in event.data.
When we create a web worker object, it continues to listen for messages, even after the external script is complete, until it is terminated.
To terminate the web worker and free up browser/computer resources, use the terminate() method:
We've .js the worker code in the file. Here's the code for the HTML page: