phpservice-workerhtml5-appcache

Two service workers for one domain


I have a web application that is currently using AppCache for offline storage. I am trying to convert this app to use Service Workers instead. I have used this source as the basis for my Service Worker, except that the Service Worker is being built using PHP so that the array of files to be cached is dynamically generated.

The problem is, the first page that the user hits is the login page, and at this stage we know nothing about the user, so we don't know which resources to cache. I solved this with AppCache by having two manifests. One manifest for the Login page and a second manifest used by all the other pages. When I did the conversion to Service Workers, I had the idea of following the same pattern; having two Service Workers - one for the Login page and one for all the other pages.

The application folder structure is like this:

-- Shared -- Pages -- Login -- Page1 -- Page2 -- Page3

The login page and the various pages, both use code in the Shared folder, so the scope of both Service Workers would have to be the root of the application. And herein lies the problem. I have now found that I can only register one Service Worker on the domain with the root scope. I could register a second Service Worker on the Login page with the /Pages/Login scope, but then this would not be able to access the shared resources. If I use the same Service Worker for both the Login and the other pages, then the registration happens on the Login page and the url list that is generated is incomplete as it only contains the resource used by the Login.

I am interest to know if anyone else has dealt with this issue and could suggest a possible direction for solving this.


Solution

  • A service worker can access resources (i.e. respond to fetch events) for URLs outside of its scope. This includes URLs at a "higher" level, such as your /Shared directory, or URLs from a completely different origin, like a CDN.

    The scope restriction determines whether or not a given service worker can control a web page at a given URL. A service worker can only control web pages whose URLs have the scope as a prefix.

    So you can create multiple service workers, and register each of them with scopes that match different URL prefixes, and they each can respond to fetch events for your shared resource URLs.

    There's more info at https://developers.google.com/web/fundamentals/primers/service-workers/lifecycle#scope_and_control