Boopathi Rajaa
Boopathi Rajaa

Reputation: 4729

Is there any effect of handling service-worker.js in the same service worker?

Let's say my service worker is sw.js. If I precache or cache this file using the same service-worker (sw.js), is there any effect ?

For example, using sw-toolbox,

toolbox.precache(['sw.js']);
toolbox.router.get('/sw.js', toolbox.cacheOnly);

and,

navigator.serviceWorker.register('sw.js');

Now, should this service-worker ever update, or will the browser allow a special fetch that checks if the URL is an exact match of the active ServiceWorkerURL and respect the 24 hour compulsory update of service worker and hit the network?

Upvotes: 1

Views: 169

Answers (2)

Boopathi Rajaa
Boopathi Rajaa

Reputation: 4729

NO.

The request for update does NOT go through the service-worker at all.

According to the ServiceWorker Spec -

Point 5.2 in Update Algorithm - https://slightlyoff.github.io/ServiceWorker/spec/service_worker/#update-algorithm

Set request’s skip service worker flag and request’s redirect mode to "error".

And fetch has a https://fetch.spec.whatwg.org/#skip-service-worker-flag which is

  1. set only for a WebSocket connection (Point 2)
  2. NOT set or unset for all requests that go out from the Document - HTTP Fetch (Point 3)
  3. This flag is NOT exposed and it's not something you can use it in your requests.

For the service worker update, this flag is set and it doesn't go through the service worker lifecycle event - fetch. Cross check with,

toolbox.router.get('/sw.js', function(...args) {
  // never called
  console.log(...args);
  return toolbox.cacheOnly(...args);
});

Use this SW code and try refreshing the page, you never get to this function for updating the service worker. This function gets called only when you,

fetch('/sw.js')

from the Document.

Upvotes: 0

Marco Castelluccio
Marco Castelluccio

Reputation: 10802

From https://www.w3.org/TR/service-workers/#service-worker-registration-update:

update() pings the server for an updated version of this script without consulting caches. This is conceptually the same operation that UA does maximum once per every 24 hours.

Also, from https://www.w3.org/TR/service-workers/#update-algorithm, step 4.8:

Let response be the result of running fetch using r, forcing a network fetch if cached entry is greater than 1 day old.

Upvotes: 1

Related Questions