针对HTML5的Web Worker使用攻略

2019-01-28 16:02:02于丽
  • var worker =new Worker("worker.js"); //创建一个Worker对象并向它传递将在新线程中执行的脚本的URL     worker.postMessage("hello world");     //向worker发送数据   
  •  worker.onmessage =function(evt){     //接收worker传过来的数据<span style="width: auto; height: auto; float: none;" id="22_nwp"><a style="text-decoration: none;" mpid="22" target="_blank" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=0&is_app=0&jk=619521ab1ccffd45&k=%BA%AF%CA%FD&k0=%BA%AF%CA%FD&kdi0=0&luki=2&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=45fdcf1cab219561&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F1183%2Ehtml&urlid=0" id="22_nwl"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">函数</span></a></span>      console.log(evt.<span style="width: auto; height: auto; float: none;" id="23_nwp"><a style="text-decoration: none;" mpid="23" target="_blank" href="http://cpro.baidu.com/cpro/ui/uijs.php?adclass=0&app_id=0&c=news&cf=1001&ch=0&di=128&fv=0&is_app=0&jk=619521ab1ccffd45&k=data&k0=data&kdi0=0&luki=4&n=10&p=baidu&q=06011078_cpr&rb=0&rs=1&seller_id=1&sid=45fdcf1cab219561&ssp2=1&stid=0&t=tpclicked3_hc&tu=u1922429&u=http%3A%2F%2Fwww%2Eadmin10000%2Ecom%2Fdocument%2F1183%2Ehtml&urlid=0" id="23_nwl"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">data</span></a></span>);              //输出worker发送来的数据   
  •  }     </script>  
  •  </head>    <body></body>  
  • </html>  

      用Chrome浏览器打开test.html后,控制台输出 ”hello world” 表示程序执行成功。

      通过这个例子我们可以看出使用web worker主要分为以下几部分

      WEB主线程:

      1.通过 worker = new Worker( url ) 加载一个JS文件来创建一个worker,同时返回一个worker实例。

      2.通过worker.postMessage( data ) 方法来向worker发送数据。

      3.绑定worker.onmessage方法来接收worker发送过来的数据。