Eivic
Eivic

Reputation: 75

Should the Service Worker file be called on each individual page?

Should the service worker file be called from each page, through header.php for example, or just in one instance from the site index?

Upvotes: 5

Views: 2287

Answers (1)

Jeff Posnick
Jeff Posnick

Reputation: 56044

Once a service worker is registered, it can take control of any page that's visited under its scope, and the browser will automatically check for updates whether or not there's another call made navigator.serviceWorker.register().

So, it is sufficient to only call navigator.serviceWorker.register() on your main entry point, and not call it again on any other pages, if you're sure that all users will pass through that entry point at least once.

That being said, there's no harm in calling navigator.serviceWorker.register() multiple times. As long as the same URL is passed in each time, it will effectively "do nothing". I'd recommend using an absolute URL, though, as relative URLs will be interpreted with the current page's URL as the base, which might lead to unexpected results if your web app uses URLs with paths that descend multiple levels. The advantage of calling navigator.serviceWorker.register() on each page is that you'll still end up with a service worker being registered even if your users navigate directly to a sub-page of your site, without visiting the main page first.

Upvotes: 14

Related Questions