今天折腾Web Worker时候需要一个很有意思问题。代码如下,有一个怪异的现象,不断刷新,SharedWorker的执行结果交替显示(一次执行,一次貌似没有执行),求大神解惑。 如果同时在两个tab页打开这个页面,每次刷新都显示正确结果。
另外想请教下,对于SharedWorker 如何调试? 当shared_worker.js 有错误的时候, 不管是worker1.onerror 还是worker1.port.onerror 都没有会触发。但是对于专用Worker 则可以捕捉到错误。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>using web worker</title>
</head>
<body>
<script>
function showMsg(msg){
var p = document.createElement('p');
p.innerHTML = msg;
document.body.appendChild(p);
}
var worker = new SharedWorker('../js/shared_worker.js');
worker.port.postMessage('60');
worker.port.onmessage = function(event){
showMsg(event.data);
};
worker.port.onerror = function(event){
showMsg(event.message);
}
var worker1 = new SharedWorker('../js/shared_worker.js');
worker1.port.postMessage('10');
worker1.port.onmessage = function(event){
showMsg("worker1: " + event.data);
};
worker1.port.onerror = function(event){
showMsg("worker1 " + event.message);
}
worker1.onerror = function(event){
showMsg("worker1 " + event.message);
}
showMsg("shared worker start.");
</script>
</body>
</html>
// shared_worker.js
function factorial(num){
var i = 1,
result = 1;
for (; i <= num; i ++){
result *= i;
}
return result;
}
var count = 0;
self.addEventListener('connect', function(event){
var port = event.ports[0]
port.onmessage = function(event){
var number = 0;
count += 1;
if (event.data){
number = parseInt(event.data, 10) || 0;
if (number > 0){
number = factorial(number);
}
}
port.postMessage("count " + count + ": " + number);
};
port.start();
});
JS脚本被缓存的问题
这样试试