首页 > 代码库 > Web worker总结

Web worker总结

Web worker有以下两种类型:

1. Dedicated worker (专用)

  属于单页面共享,目前除了IE之外各浏览器支持比较广泛;

// 页面中执行
var
work1 = window.work1 = new Worker("worker_1.js");work1.onmessage = function (e) {  console.log("Receive message:", e.data, e);};work1.postMessage("data to worker.");
// worker_1.js: 单独线程中执行onmessage = function (e) {    console.log("Receive from main:", e.data, e);};var count = 0;setInterval(function () {    postMessage("Message data" + count++);}, 5000);

 

2. SharedWorker

  多页面共享,可以当做多页面之间交互的一种解决方案;当前Firefox 29以上才支持;

// 页面中执行
if
(!window.SharedWorker){ alert("Your browser does not support SharedWorker!"); return;}var work2 = window.work2 = new SharedWorker("worker_2.js");work2.port.onmessage = function (e) { console.log("Receive:", e.data, e);};work2.port.start();//work2.port.postMessage("data to worker.");
// worker_2.js: 单独线程中执行
var
userCount = 0;var portList = [];onconnect = function (e) { var port = e.ports[0]; portList.push(port); port.postMessage("Accept new user with count:" + userCount); port.onmessage = function (e) {
    // 向所有接受者发送
    for(var i=0; i<portList.length; i++){      portList[i].postMessage("Send accepted msg:" + portList.length + i + e.data);    }  };};

 

  它们的scope|context并不是window,均继承自WorkerGlobalScope,前者为 DedicatedWorkerGlobalScope,后者为 SharedWorkerGlobalScope;在Chrome 38版本上后者不支持console的输出,目前MDN也没有相应的文档;

 

 

参考资料:

1. Dedicated worker    https://developer.mozilla.org/en-US/docs/Web/API/Worker

2. SharedWorker       https://developer.mozilla.org/en-US/docs/Web/API/SharedWorker

 

Web worker总结