將函式傳給webworker

zyip發表於2016-12-21

 

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')

 

相關文章