What is a web worker?
We've always emphasized that JavaScript is single-threaded, but the advent of web workers makes JavaScript possible to run on multiple threads, but the Web worker itself is suitable for complex, CPU-intensive operations that cannot manipulate windows, document, Parent object, so essentially JavaScript is a single thread.
Here, we just give a simple example, see how the Web worker is running, after all, is the HTML5 specification, the current browser support is not very good.
Web worker is a JavaScript running in the background, independent of other scripts, without affecting the performance of the page. You can also do whatever you want to do, without affecting clicks and other actions.
Why do I need a web worker?
For JavaScript that is time-consuming and does not manipulate the DOM, we can use Web worker to enhance performance.
What does web worker have to pay attention to?
- Not all browsers are supported, check whether the browser supports it before use.
- Web workers run in external files , so they cannot access the following JavaScript objects.
- Understanding Good worker,worker is often translated into threads or processes in the computer field. The same is true of the worker here. We need to treat it right.
Web Worker Instance
To create an worker.js external file:
var 0 ; setinterval (function () { postMessage (i++);
The HTML file is as follows:
<! DOCTYPE html>"en">"UTF-8"> <title>Document</title>"result"></span></p> <button onclick="Start ()">web worker starts work </button> <button onclick="Stop ()">web worker End work </button> <script>varW; function Start () {if(typeofWorker! ='undefined') {W=NewWorker ('Worker.js'); W.onmessage= function (Event) {document.getElementById ('result'). InnerHTML =Event. Data; } } Else{document.getElementById ('result'). InnerHTML ='your browser does not support Web worker'; }} function Stop () {w.terminate (); W=undefined; } </script></body>That is, the first judge: whether to support the worker constructor, if supported, pass a JS file to create an instance of this file, then you can call the message event, receive data from the Worker.js.
Note: You must test on the server, or there will be cross-domain issues.
In the end, I can see the effect.
Code Address: Https://github.com/zzw918/cross-origin/tree/master/webWorker
Web worker Principle