What's the difference between Shared Worker and Worker in HTML5?
JavascriptHtmlWeb WorkerJavascript Problem Overview
After reading this blog post: http://www.sitepoint.com/javascript-shared-web-workers-html5/
I don't get it. What's the difference between a Worker
and a SharedWorker
?
Javascript Solutions
Solution 1 - Javascript
Very basic distinction: a Worker
can only be accessed from the script that created it, a SharedWorker
can be accessed by any script that comes from the same domain.
Solution 2 - Javascript
SharedWorker's seem to have more functionality then Worker.
Among that functionality is :
- A shared global scope. All
SharedWorker
instances share a single global scope.
W3C Spec:
WHATWG Spec:
Solution 3 - Javascript
To anyone considering using SharedWorker -- Apple removed support of SharedWorker
from WebKit in 2015. In their current roadmap there is no plan for reimplementation. Support for Service Workers is currently under development for WebKit and offer similar capabilities (see here for comparisons).
You can follow the development (aka Safari support) of ServiceWorkers in WebKit here.
Solution 4 - Javascript
A shared worker can work with multiple connections. It posts messages to ports to allow communication between various scripts.
A dedicated worker on the other hand is simply tied to its main connection and cannot post messages to other scripts (workers).
Solution 5 - Javascript
Shared worker allow all front page context script, which call constructor: new SharedWorker("path-to-shared-worker-file.js") to share the same instance of shared worker file running in the background context(another thread of running javascript in the back).
for example, when webpage #1 calling that constructor, if found there is no shared worker loaded up in the back yet, it will cause the background context to download the file and load it up, then later when webpage #2 calling that same constructor(same file path), it found there is an existing shared worker running, it will just using the same one. When worker.port.start() function invoked, it will cause shared worker file onconnect event handler invoked to register caller and obtain the handle to communicate the client port(for postMessage back for example).
However worker, every webpage above will load up one worker file in the background for every single front page, which is not shared the same worker.js instance.