May 03, 2021 HTML5
Web worker is JavaScript running in the background that does not affect the performance of the page, and a better explanation is that you can use an easy way provided by web worker to run scripts for web content in background threads that do not interfere with the user interface while performing tasks!
When a script is executed in an HTML page, the state of the page is non-responsive until the script is complete.
Web worker is JavaScript that runs in the background, independent of other scripts, and does not affect the performance of the page. You can continue to do whatever you want: tap, pick content, and so on, while the web worker runs in the background.
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!
Now let's create our web worker in an external JavaScript.
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:
Because the web worker is in an external file, they cannot access the following JavaScript object: