Service Worker vs Shared Worker - javascript

What is the difference between Service Worker and Shared Worker?
When should I use Service Worker instead of Shared Worker and vice versa?

A service worker has additional functionality beyond what's available in shared workers, and once registered, they persist outside the lifespan of a given web page.
Service workers can respond to message events, like shared workers, but they also have access to additional events. Handling fetch events allows service workers to intercept any network traffic (originating from a controlled page) and take specific actions, including serving responses from a Request/Response cache. There are also plans to expose a push event to service workers, allowing web apps to receive push messages in the "background".
The other major difference relates to persistence. Once a service worker is registered for a specific origin and scope, it stays registered indefinitely. (A service worker will automatically be updated if the underlying script changes, and it can be either manually or programmatically removed, but that's the exception.) Because a service worker is persistent, and has a life independent of the pages active in a web browser, it opens the door for things like using them to power the aforementioned push messaging—a service worker can be "woken up" and process a push event as long as the browser is running, regardless of which pages are active. Future web platform features are likely to take advantage of this persistence as well.
There are other, technical differences, but from a higher-level view, those are what stand out.

A SharedWorker context is a stateful session and is designed to multiplex web pages into a single app via asynchronous messaging (client/server paradigm). Its life cycle is domain based, rather than single page based like DedicatedWorker (two-tier paradigm).
A ServiceWorker context is designed to be stateless. It actually is not a persistent session at all - it is the inversion of control (IoC) or event-based persistence service paradigm. It serves events, not sessions.
One purpose is to serve concurrent secure asynchronous events for long running queries (LRQs) to databases and other persistence services (ie clouds). Exactly what a thread pool does in other languages.
For example if your web app executes many concurrent secure LRQs to various cloud services to populate itself, ServiceWorkers are what you want. You can execute dozens of secure LRQs instantly, without blocking the user experience. SharedWorkers and DedicatedWorkers are not easily capable of handling many concurrent secure LRQs. Also, some browsers do not support SharedWorkers.
Perhaps they should have called ServiceWorkers instead: CloudWorkers for clarity, but not all services are clouds.
Hopefully this explanation should lead you to thinking about how the various Worker types were designed to work together. Each has its own specialization, but the common goal is to reduce DOM latency and improve user experience in web based applications.
Throw in some WebSockets for streaming and WebGL for graphics and you can build some smoking hot web apps that perform like multiplayer console games.

2022 06 Update
WebKit added support for the SharedWorker recently, see the details of the resolution in the issue link mentioned below.
2020 11 Update
Important detail for anyone interested in this discussion: SharedWorker is NOT supported by WebKit (was intentionally removed ~v6 or something).
WebKit team are explicitly suggesting to use ServiceWorker wherever SharedWorker might seem relevant.
For a community wish to get this functionality back to WebKit see this (unresolved as of now) issue.

Adding up to the previous great answers.
As the main difference is that ServiceWorker is stateless (will shut down and then start with clear global scope) and SharedWorker will maintain state for the duration of the session.
Still there is a possibility to request that ServiceWorker will maintain state for the duration of a message handler.
s.onmessage = e => e.waitUntil((async () => {
// do things here
// for example issue a fetch and store result in IndexedDb
// ServiceWorker will live till that promise resolves
})())
The above code requires that the ServiceWorker will not shut down till the promise given as the parameter to waitUntil resolves. If many messages are handled concurrently in that manner ServiceWorker will not shut down untill all promises are resolved.
This could be possibly used to prolong ServiceWorker life indefinitely making it effectively a SharedWorker. Still, do keep in mind that browser might decide to force a shut down if ServiceWorker goes on fo too long.

Related

Addressing Privacy Concerns Regarding Push Notifications

To facilitate push notifications, is it absolutely necessary for a browser to host servers to accomplish this?
Each time I launch Firefox, prior to going to any websites, Firefox makes a connection to an Amazon AWS server that it maintains 24/7 (as long as the web browser it open).
Anyone who knows how to monitor their connections can verify what I'm saying. As soon as you launch Firefox, (prior to going to any websites) it will make and sustain a connection to an ip address like this one:
As long as Firefox remains open, you'll sustain a connection to an Amazon AWS server like the one above.
Is this really just the nature of push notifications? It is a technology that must maintain a 24/7 connection to your computer even if you haven't even navigated to a website?
So by design, the spec prescribed that a browser maker must provide a 24/7 service to facilitate this technology?
If this is the only way to facilitate this technology, then I'd be interested in running my own service to facilitate it. I don't feel comfortable with my web-browser maintaining a 24/7 connection to a server that's also controlled by the maker of the web-browser.
While the intention of this is probably divine, I consider it a slippery slope. A web browser that maintains a 24/7 connection with its creators, over the long run, I feel will evolve to communicate much more than just push notifications.
If you can put my concerns to rest. Please do.
My ultimate question is this:
If what I've described above, is simply the nature of the spec (as written), then is it possible to host you're own push notification service, so that your web browser uses your own service, instead of some 3rd party (like the maker of your web-browser)?

What are the restrictions on what can and cannot be done in a a service worker?

Further to Can I http poll or use socket.io from a Service Worker on Safari iOS? what is the list of what can and cannot be done in a service worker? The answer referenced above says "You cannot ... have an open connection of any sort to your server" which makes sense, but where is that fact documented and how is the restriction enforced?
For example, are certain browser APIs unavailable to Service Workers? or is there an execution quota which prevents a long running process?
Eg. if my service worker has ...
setInterval (()=>{console.log('foo'), 1000})
... will it throw an exception?, will it run and then fail? is the behaviour browser dependent?
Service Workers are only supposed to process attached events.
And those are to be registered by some script from the outside.
Even delaying the execution is not supported in some cases on Safari - Event.waitUntil(promise).
Once your event queue is empty, your user agent is supposed to decide wether it kills of the service. There is no guarantee that anything from then on is going to get executed.
A service worker is not just another thread but a very specific kind of thread. As in it is meant to intercept network and resource fetch requests and do something with it. In its most basic form, it caches if the network is not available, but it can also return a different resource than what was requested, an older version or a placeholder etc.
Eg. if my service worker has ... setInterval (()=>{console.log('foo'),
1000}) ... will it throw an exception? will it run and then fail? is
the behaviour browser dependent?
It will likely work. However, there is very little point of doing this since you neither have any DOM access nor can you directly interact with the user. At most, you can print out errors and warnings though I don't know what warning would require interval polling.
From the question, it sounds you are trying to accomplish some background work without blocking the main thread. In which case, the more generic type (the Worker API) is your friend.

What is service worker in react js

When creating a react app, service worker is invoked by default. Why service worker is used? What is the reason for default invoking?
You may not need a service worker for your application. If you are creating a project with create-react-app it is invoked by default
Service workers are well explained in this article. To Summarise from it
A service worker is a script that your browser runs in the
background, separate from a web page, opening the door to features
that don't need a web page or user interaction. Today, they already
include features like push notifications and background sync and have
ability to intercept and handle network requests, including
programmatically managing a cache of responses.
In the future, service workers might support other things like
periodic sync or geofencing.
According to this PR to create-react-app
Service workers are introduced with create-react-app via
SWPrecacheWebpackPlugin.
Using a server worker with a cache-first strategy offers performance
advantages, since the network is no longer a bottleneck for fulfilling
navigation requests. It does mean, however, that developers (and
users) will only see deployed updates on the "N+1"
visit to a page, since previously cached resources are updated in the
background.
The call to register service worker is enabled by default in new apps but you can always remove it and then you’re back to regular behaviour.
In simple and plain words, it’s a script that browser runs in the background and has whatsoever no relation with web pages or the DOM, and provide out of the box features. It also helps you cache your assets and other files so that when the user is offline or on slow network.
Some of these features are proxying network requests, push notifications and background sync. Service workers ensure that the user has a rich offline experience.
You can think of the service worker as someone who sits between the client and server and all the requests that are made to the server pass through the service worker. Basically, a middle man. Since all the request pass through the service worker, it is capable to intercept these requests on the fly.
I'd like to add 2 important considerations about Service Workers to take into account:
Service Workers require HTTPS. But to enable local testing, this restriction doesn't apply to localhost. This is for security reasons as a Service Worker acts like a man in the middle between the web application and the server.
With Create React App Service Worker is only enabled in the production environment, for example when running npm run build.
Service Worker is here to help developing a Progressive Web App. A good resource about it in the context of Create React App can be found in their website here.

Two service workers at the same time

I'd like to use two service workers on my site: one to provide a classic offline cache (/sw.js) for my PWA and another for something like a local database "server" which uses background sync and push (/sw-db.js). Since the latter tends to do heavy work (blocking the event loop for a few ms) it's better to keep it separate.
Since the database sw is not used for fetch requests, I would give it a dummy scope, whereas sw.js is scoped for the whole domain.
Does the first, which responds to "fetch" events, also serve the code/URL for /sw-db.js (keeping it somewhat in-sync with site updates) or are service workers always updated via network.
The sw.js script URL that you pass in to navigatior.serviceWorker.register('/path/to/sw.js') will always be fetched bypassing any other service workers when it's time to check for updates. So to answer your question, the other service worker's fetch handler won't be triggered.
The HTTP cache does come into play whenever there's an update check for a service worker script. So you should make sure you're setting proper HTTP cache control headers for your use case.
Usually, a service worker update check is triggered due to a navigation to a page controlled by a service worker, but if you have a service worker with a "dummy" scope, it won't end up controlling any pages. That being said, when a service worker handlers sync or push events you'll also end up triggering the update check. I'm not sure if every sync or push triggers the check, or just a subset of them, such as the ones which cause a new service worker to spawn. But it will happen at least some of the time.

Prevent Service Worker from automatically stopping

Service Worker seems to automatically stop at some point. This behaviour unintentionally closes the WebSocket connection established on activate.
When and Why does it stop? How can I programmatically disable this unexpected action to keep Service Worker stay running?
What you're seeing is the expected behavior, and it's not likely to change.
Service workers intentionally have very short lifespans. They are "born" in response to a specific event (install, activate, message, fetch, push, etc.), perform their task, and then "die" shortly thereafter. The lifespan is normally long enough that multiple events might be handled (i.e. an install might be followed by an activate followed by a fetch) before the worker dies, but it will die eventually. This is why it's very important not to rely on any global state in your scripts, and to bootstrap any state information you need via IndexedDB or the Cache Storage API when your service worker starts up.
Service workers are effectively background processes that get installed whenever you visit certain web pages. If those background processes were allowed to run indefinitely, there's an increased risk of negative impact on battery and performance of your device/computer. To mitigate this risk, your browser will only run those processes when it knows it's necessary, i.e. in response to an event.
A use case for WebSockets is having your client listen for some data from the server. For that use case, the service worker-friendly alternative to using WebSockets is to use the Push Messaging API and have your service worker respond to push events. Note that in the current Chrome implementation, you must show a user-visible notification when handling a push event. The "silent" push use case is not supported right now.
If instead of listening to data from the server, you were using WebSockets as a way of sending data from your client to your server, there's unfortunately no great service worker-friendly way of doing that. At some point in the future, there may be a way of registering your service worker to be woken up via a periodic/time-based event at which point your could use fetch() to send data to the server, but that's currently not supported in any browsers.
P.S.: Chrome (normally) won't kill a service worker while you have its DevTools interface open, but this is only to ease debugging and is not behavior you should rely on for a real application.
The Theory
Jeff's answer explains the theory part - why and how, in detail.
It also includes many good points on why you might not want to pursue this.
However, in my case, the downsides are nonexistent since my app will run on desktop machines which are reserved only to run my app. But I needed to keep the SW alive even when the browser window is minimized. So, if you are working on a web app which will run on variety of devices, keeping the SW alive might not be a good idea, for the things discussed in above answer.
With that said, let's move onto the actual, practical answer.
My "Practical" Solution
There should be many ways to keep the SW alive, since SWs stay alive a bit after responding to many different events. In my case, I've put a dummy file to server, cached it in the SW, and requested that file periodically from the document.
Therefore the steps are;
create a dummy file on the server, say ping.txt
cache the file on your SW
request that file from your html periodically to keep the SW alive
Example
// in index.html
setInterval(function(){
fetch('/ping.txt')
}, 20000)
The request will not actually hit the server, since it will be cached on the SW. Nonetheless, that will keep the SW alive, since it will respond to the fetch even evoked by the request.
PS: I've found 20 seconds to be a good interval to keep the SW alive, but it might change for you, you should experiment and see.

Categories