Wernight
Wernight

Reputation: 37600

Should service worker script be loaded first?

To initialize a Service Worker one has to include in thead <head> something like:

<script>
if ('serviceWorker' in navigator) {
  navigator.serviceWorker.register('/my-sw.js');
}
</script>

I found that in some example pages this isn't the first script (e.g. flipkart.com) of the page. Shouldn't it be the first one so that pre-caching and other features can be used ASAP? Does or doesn't the order actually matter for this script and it could well be at the bottom of the page outside </head>?

Upvotes: 0

Views: 725

Answers (1)

Vivek Pratap Singh
Vivek Pratap Singh

Reputation: 9974

Registering a service worker will cause the browser to start the service worker install step in the background. If successful, the service worker is executed in a ServiceWorkerGlobalScope; this is basically a special kind of worker context, running off the main script execution thread, with no DOM access.

Being specific with your question, The order of service worker registration script doesn't matter, As an after a service worker is installed and the user navigates to a different page or refreshes, the service worker will begin to receive fetch events.

Upvotes: 1

Related Questions