html5 Worker学习
HTML:
<!DOCTYPE HTML> <html> <head> <meta charset="utf-8" /> <title>HTML5 线程交互例子</title> <script type="text/javascript" src="mainthread.js"> </script> </head> <body> <input type="text" id="inputedInteger" /> <input type="button" value="点击让主线程把这个数值发送给后台线程1" onclick="html5Worker()" /> <p id="result"></p> </body> </html>
mainthread.JS
function html5Worker() { //判断浏览器是否支持 if (typeof (Worker) == "undefined") { console.log("对不起你的浏览器不支持worker"); return; } //创建web worker实例 var worker1 = new Worker("thread1.js"); var integerInput = document.getElementById("inputedInteger").value; var num = parseInt(integerInput, 10); //跨文档消息传输Cross Document Messaging。 //postMessage发送消息给thread1 worker1.postMessage(num + "我是主线程的值我将发送给thread1 "); //onmessage事件监听器 //当 web worker 传递消息时,会执行事件监听器中的代码。event.data 中存有来自 event.data 的数据。 worker1.onmessage = function (event) { //取得从后台线程1(thread1)信息 var data = event.data; var worker2 = new Worker("thread2.js"); worker2.postMessage(data + " 我是主线程的值我将发送给thread2"); worker2.onmessage = function (event) { document.getElementById("result").innerHTML = event.data; } }; }
thread1.js
onmessage = function (event) { var result = event.data + " 我是thread1接收的值我将返回 "; console.log("thread1"); //把这个requst发送回主线程 (也就是创建这个worker1的线程) postMessage(result); }
thread2.js
onmessage = function(event) { // 获取从主线程传来的数据 var result = event.data + " 我是thread2接收的值我将返回"; console.log("thread2"); //把这个result发送回主线程 (也就是创建这个worker2的线程) postMessage(result); }
运行结果:
注意的是要发布到服务器才能运行否则出现:
Uncaught SecurityError: Failed to construct 'Worker': Script at 'xxxxthread1.js' cannot be accessed from origin 'null'.
总结 :
1:创建worker实例并传递对应的js文件
2:发送消息 postMessage()
3:监听消息 onmessage
4:停止terminate()方法
5:onerror错误异常
监听消息也可以用下列方式.
//google 或者ie方式注册事件 if (typeof window.addEventListener != 'undefined') { window.addEventListener('message', messageChange, false); } else if (typeof window.attachEvent != 'undefined') { window.attachEvent('onmessage', messageChange); }