HTML5 Web Workers

Web Workers

The concept of web workers is introduced in the html5 specification to solve the problem that client-side JavaScript cannot be multi-threaded. The worker defined refers to the parallel thread of the code, but the web The worker is in a self-contained environment and cannot access the window object and document object of the main thread. It can only communicate with the main thread through the asynchronous message passing mechanism

We need to put the JavaScript code that we want to execute separately into a separate js file, and then call the Worker constructor in the page to create a thread. The parameter is the file path. If the parameter storage is a relative address, then the script containing the statement that calls the Worker constructor should be used as a reference. If it is an absolute path, It is necessary to ensure the same origin (protocol + host + port). This file does not require us to use script tags to display references on the page

var worker=new Worker('js/worker.js');

Simple Small example

Display all the numbers from 0 to 10000 that can be divisible by n on a page. Of course, we don’t use i*n to make the calculation a little more complicated

index.html

<!DOCTYPE html>
<html>
<head>
    <title>Web Workers</title>
</head>
<body>
  <h1>Web Workers</h1>
      <div id="test" style="width:500px;"></div>
    <script type="text/javascript">
        var worker=new Worker('js/worker.js');
        worker.postMessage({
            n:69
        });
        worker.onmessage=function(e){
            var test=document.getElementById('test').innerHTML=e.data;        
        };
    </script>
</body>
</html>

/js/worker.js

function calc(n){
    var result=[];
    for(var i=1;i<10000;i++){
        var tem=i;
        if(i%n==0){
            if(i%(10*n)==0){
                tem+='<br/>';
            }
            result.push(tem);
        }
    }

    self.postMessage(result.join(' '));
    self.close();
}

onmessage=function(e){
    calc(e.data.n);
};

Display effect:

1018.png

Create web worker file

Now, Let's create our web worker in an external JavaScript.

Here we create the counting script. The script is stored in the "demo_workers.js" file:

var i=0;

function timedCount()
{
i=i+1;
postMessage(i);
setTimeout("timedCount()",500);
}

timedCount();

The important part of the above code is the postMessage() method - it is used to pass a message back to the HTML page.

Note: web workers are usually not used for such simple scripts, but for more CPU-intensive tasks.

Create Web Worker Object

We already have the web worker file, now we need to call it from the HTML page.

The following code detects whether the worker exists. If not, - it creates a new web worker object and then runs the code in "demo_workers.js":

if(typeof (w)=="undefined")
{
w=new Worker("demo_workers.js");
}

Then we can happen from the web worker and Received the message.

Add an "onmessage" event listener to the web worker:

w.onmessage=function(event){
document.getElementById("result").innerHTML= event.data;
};

<pWhen web="" worker="" delivers a message, the code in the event listener is executed. event.data="" contains data from ="" event.data="".

Terminate Web Worker

After we create the web worker object, it will continue to listen for messages (even after the external script completes) until its until terminated.

To terminate the web worker and release browser/computer resources, please use the terminate() method:

w.terminate();




Continuing Learning
||
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> <!-- web worker是运行在后台的javascript,不会影响页面的性能 --> <p>计数:<output id="result"></output></p> <button onclick="startWorker()">开始worker</button> <button onclick="endWorker()">停止worker</button> <br><br> <script type="text/javascript"> var w; function startWorker(){ if(typeof(Worker)!="undefined"){//浏览器支持web worker if(typeof(w)=="undefined"){//w是未定义的,还没有开始计数 w = new Worker("webworker.js");//创建一个Worker对象,利用Worker的构造函数 } //onmessage是Worker对象的properties w.onmessage = function(event){//事件处理函数,用来处理后端的web worker传递过来的消息 document.getElementById("result").innerHTML=event.data; }; }else{ document.getElementById("result").innerHTML="sorry,your browser does not support web workers"; } } function endWorker(){ w.terminate();//利用Worker对象的terminated方法,终止 w=undefined; } </script> <p>在后台运行的web worker js文件,webworker.js 才能实现效果<br> var i = 0; <br> function timeCount(){ <br> i = i + 1; <br> postMessage(i);//postMessage是Worker对象的方法,用于向html页面回传一段消息 <br> setTimeout("timeCount()",500);//定时任务 <br> } <br> timeCount();//加1计数,每500毫秒调用一次</p> </body> </html>
submitReset Code