本文主要包含HTML5,Worker等相关知识,佚名 希望在学习及工作中可以帮助到您
Web Workers 是 HTML5 提供的一个javascript多线程解决方案,我们可以将一些大计算量的代码交由web Worker运行而不冻结用户界面。
一:如何使用Worker
Web Worker的基本原理就是在当前javascript的主线程中,使用Worker类加载一个javascript文件来开辟一个新的线程,起到互不阻塞执行的效果,并且提供主线程和新线程之间数据交换的接口:postMessage,onmessage。
那么如何使用呢,我们看一个例子:
- //worker.js
- onmessage =function (evt){
- var d = evt.data;//通过evt.data获得发送来的数据
- postMessage( d );//将获取到的数据发送会主线程
- }
HTML页面:test.html
- <!DOCTYPE HTML>
- <html>
- <<span style="width: auto; height: auto; float: none;" id="20_nwp"><a style="text-decoration: none;" mpid="20" 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=head&k0=head&kdi0=0&luki=6&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="20_nwl"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">head</span></a></span>>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
- <script type="text/<span style="width: auto; height: auto; float: none;" id="21_nwp"><a style="text-decoration: none;" mpid="21" 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=javascript&k0=javascript&kdi0=0&luki=9&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="21_nwl"><span style="color:#0000ff;font-size:14px;width:auto;height:auto;float:none;">javascript</span></a></span>">
- //WEB页主线程
- 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"