The best HTML5 Web Workers Tutorial In 2024, In this tutorial you can learn What is a Web Worker?,Browser Support,HTML5 Web Workers examples,Examples,Detecting whether the browser supports the Web Worker,Create a web worker file,Create a Web Worker Object,Web Worker termination,Complete Web Worker example code,Examples,Web Workers and the DOM,
web worker run JavaScript in the background and does not affect the performance of the page.
When executing a script in an HTML page, the page state is unresponsive until the script is complete.
web worker run JavaScript in the background, independent of other scripts will not affect the performance of the page. You can continue to do whatever is willing to do: Click to select content, etc., at a time when web worker runs in the background.
Internet Explorer 10, Firefox, Chrome, Safari and Opera support Web workers.
The following example creates a simple web worker, counting in the background:
demo_workers.js file code:
Before creating a web worker, please check the user's browser supports it:
Now, let's create our web worker in an external JavaScript.
Here, we've created a script count. The script is stored in the "demo_workers.js" file:
Important part of the code above is postMessage () method - it is used to return some HTML page news.
Note: web worker is generally not used for such simple scripts, but for more CPU-intensive tasks.
We already have a web worker file, and now we need to call it from an HTML page.
The following code detects the presence of worker, if there is no - it creates a new web worker object and then run "demo_workers.js" code:
We can then take place and receive messages from the web worker.
Add to web worker a "onmessage" event listeners:
When we create a web worker object, it will continue to listen for messages (even after the completion of an external script) until it is terminated by.
To terminate a web worker, and release the browser / computer resources, use the terminate () method:
We've seen .js file Worker code. Here is the code HTML page:
Since the web worker in an external file, they can not access the JavaScript object the following example: