将函数传给webworker

 

var zWorker = function (func,cb){
var node = document.createElement('script'),workerId='worker' + Date.now()
node.setAttribute('type',"javascript/worker")    
node.setAttribute('id',workerId)
//node.innerHTML = 'function fun1(str){alert(str)}'
//node.innerHTML = 'self.onmessage=function(e){console.log(e.data);self.postMessage("msg from worker");}'
node.innerHTML = 'self.onmessage=' + func + '; self.onmessage=function(e){console.log(e.data);self.postMessage("msg from worker");}'
document.body.append(node)
var blob = new Blob([ document.querySelector('#' + workerId ).textContent ], { type: "text/javascript" })
var worker = new Worker(window.URL.createObjectURL(blob));
worker.onmessage = function(e) {
              //console.log("Received: " + e.data);
cb && cb(e.data)
        }
return worker
}

 

var workerInst = zWorker(function(str){console.log(str)},function(str){alert(str)})
workerInst.postMessage('hello')

 

posted @ 2016-12-21 17:21  zyip  阅读(617)  评论(0编辑  收藏