Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between serviceWorker.getRegistration and serviceWorker.ready.then

I'm writing my first app with Service Workers and am trying to get the registration in order to interact with the pushManager.

I can do this with either of the following:

nagivator.serviceWorker.getRegistration()

or

navigator.serviceWorker.ready.then()

Which should I use and what is the difference?

like image 727
owencm Avatar asked Mar 01 '15 02:03

owencm


2 Answers

As far I can understand the first one does not wait until the ServiceWorkerRegistration has an active ServiceWorker. The last one does.

like image 180
Sandro Paganotti Avatar answered Oct 16 '22 09:10

Sandro Paganotti


Using ready makes things simpler because it is "designed in a way that the returned promise will never reject. Instead, it waits until the promise resolves with a service worker registration that has an active worker." (see the definition of ready in the Service Worker spec).

Wich in turn will result in fewer failure modes when calling Push API's subscribe method.

Calling subscribe from a getRegistration() context, adds a few extra failure modes:

[...snip...]

  1. If registration has no active worker, run the following substeps:
    1. If registration has no installing worker and no waiting worker, reject promise with a DOMException whose name is "InvalidStateError" and terminate these steps.
    2. Wait for the installing worker or waiting worker of registration to become its active worker.
    3. If registration fails to activate either worker, reject promise with a DOMException whose name is "InvalidStateError" and terminate these steps.
    4. Once registration has an active worker, proceed with the steps below.

[...snip...]

like image 20
Kenji Baheux Avatar answered Oct 16 '22 09:10

Kenji Baheux