Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens to JS ServiceWorker when I close the tab

Tags:

javascript

When you close all tabs doing web worker, worker is shut down.

Does the same thing happens to service worker?

like image 268
azurinko Avatar asked Sep 18 '17 14:09

azurinko


1 Answers

There are two relevant aspects to this:

  1. Service worker registration, which is the record held in the browser to say "for this URL, these events should be handled by this script," and

  2. Service worker activation, which is when your worker code is loaded in memory and either handling a request or waiting for one

A service worker remains registered across browser sessions (spec link). So if you exit the browser entirely (or even reboot the computer), the registration persists; the worker will get activated if you go to the relevant scope URL and an event it's registered to handle occurs.

A service worker is activated when it's needed to handle an event, and may be terminated the moment it has no events to handle (spec link). It's up to the host environment (the browser) when and whether it does that. The browser might keep the worker activated if there's no memory pressure or similar (even if all tabs using the worker's scope URL are closed), though that seems unlikely; it might be keep it in memory when there's still at least one tab using its scope URL even if the worker is currently idle; or it might terminate the worker the instant it doesn't have any requests to handle. It's up to the host environment to balance the cost of keeping the service worker in memory against the cost of starting it up when it's needed again.

It's a useful mental model to assume that the host will be really aggressive and terminate the worker the instant it isn't actively needed, which is why a previous version of this answer called them "extremely short lived." But whether that's literally true in any given host environment is up to the environment and its optimizations.

like image 189
T.J. Crowder Avatar answered Oct 09 '22 13:10

T.J. Crowder