javascript - SharedWorker 没有执行?
黄舟
黄舟 2017-04-10 16:51:24
0
1
309

今天折腾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();
});
黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(1)
巴扎黑

JS脚本被缓存的问题
这样试试

var worker = new SharedWorker('../js/shared_worker.js?time='+new Date().getTime());
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template