Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
620 views
in Technique[技术] by (71.8m points)

javascript - Do Shared Web Workers persist across a single page reload, link navigation

Shared Web Workers are designed to allow multiple pages from the same site (origin) to share a single Web Worker.

However, it's not clear to me from the spec (or other tutorials and information on Shared Workers) whether the Shared Worker will persist if you have only one window/tab from the site and you navigate to another page on the same site.

This would be most useful in the case of a WebSocket connection from the Shared Worker that stays connected as the site is navigated. For example, imagine a stock ticker or chat area that would persist (without having to reconnect the WebSocket) even while the site is navigated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have done some testing to find out the answer to this in practice.

Firefox does not yet support creating WebSocket connections from Web Workers: https://bugzilla.mozilla.org/show_bug.cgi?id=504553 So Firefox is not relevant until that bug is resolved.

IE 10 doesn't have support for Shared Web Workers so it's not relevant either. So that leaves Chrome.

Here is an example to test shared web workers.

First the HTML:

<!DOCTYPE html>
<html>
<body>
    <a href="shared.html">reload page</a>
    <script>
        var worker = new SharedWorker("shared.js");
        worker.port.addEventListener("message", function(e) {
            console.log("Got message: " + e.data);
        }, false);
        worker.port.start();
        worker.port.postMessage("start");
    </script>
</body>
</html>

Then the implementation of the shared worker itself in shared.js:

var connections = 0;

self.addEventListener("connect", function(e) {
    var port = e.ports[0];
    connections ++;
    port.addEventListener("message", function(e) {
        if (e.data === "start") {
            var ws = new WebSocket("ws://localhost:6080");
            port.postMessage("started connection: " + connections);
        }
    }, false);
    port.start();
}, false);

Test results in Chrome 20 (the answer):

When the page is loaded simultaneously in two separate tabs, the connection count grows each time one of the pages is reloaded or the self-referential link is clicked.

If only a single instance of the page is loaded then the connection count never changes when the page is reloaded or the link is clicked.

So, in Chrome 20: Shared Web Workers do not persist across page reloads and link navigation clicks.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...