HTML5 Web Workers 简单例子
1.Worker用js代码:
1 function messageHandler(e) 2 { 3 postMessage("Worker has received Message :"+e.data); 4 } 5 addEventListener("message",messageHandler,true)
2.主页代码:
1 <head> 2 <title>Web Workers</title> 3 <meta charset="utf-8"> 4 <p id='support'> 5 Sorry Your Browser Does Not Support Web Workers! 6 </p> 7 <script type="text/javascript"> 8 var workers=[]; 9 10 function messageHandler(e) 11 { 12 console.info("browser:"+e.data); 13 } 14 function initWorker() 15 { 16 var src='http://localhost:8000/workerTest.js'; 17 var worker=new Worker(src); 18 worker.addEventListener("message",messageHandler,true); 19 worker.addEventListener("error",errorHandler,true); 20 return worker; 21 } 22 function startWorker() 23 { 24 var worker=initWorker(); 25 worker.postMessage("you're the "+workers.length+"th worker!"); 26 workers.push(worker); 27 } 28 function terminateWorker() 29 { 30 for(var i=0;i<workers.length;i++) 31 { 32 workers[i].terminate(); 33 } 34 workers=[]; 35 } 36 function loadDemo(){ 37 console.info("loaded"); 38 if(typeof(Worker)!="undefined") 39 { 40 document.getElementById("support").innerHTML="Excellent! Your Browser Support Web Workers!"; 41 document.getElementById("b1").onclick=startWorker; 42 document.getElementById("b2").onclick=terminateWorker; 43 } 44 } 45 function errorHandler(e) 46 { 47 console.info("Error: "+e.message); 48 } 49 window.addEventListener("load",loadDemo,true); 50 </script> 51 <button id='b1'>start!</button> 52 <button id='b2'>Terminate!</button> 53 </head> 54 <body> 55 </body>
运行: (需要防止跨域访问造成的, SECURITY_ERR: DOM Exception 18)
把他们放在同一目录下,在该目录部署一个简单的HTTP服务器。
用Python的 python -m SimpleHTTPServer 建立一个应用服务器,
然后把地16行的 :
var src='http://localhost:8000/workerTest.js'; 改成正确的路径就可以运行了:
本例的执行效果为(控制台输出):
HTML5的 web worker api 使用起来很方便,如果有大量JS需要运行可以考虑使用,可以防止页面卡死,充分利用多核CPU。