TL;DR - I want my service worker to activate immediately after the first visit to my site, instead of after the first refresh.
Details:
I have built a progressive web app using service worker, but have noticed that on the first load (when the SW is installed) it will not intercept any network requests until the user refreshes the page.
Is there anything I can do to have the service worker start immediately intercepting requests after it is installed?
Service workers are specialized JavaScript assets that act as proxies between web browsers and web servers. They aim to improve reliability by providing offline access, as well as boost page performance.
The Fetch API is a part of the Service Worker global scope, and you can use it to make HTTP requests inside any Service Worker.
Using a Service worker you can easily set an app up to use cached assets first, thus providing a default experience even when offline, before then getting more data from the network (commonly known as Offline First).
You can indeed, by using a combination of skipWaiting
and clients.claim
as seen below.
This will cause the service worker to immediately take control of network requests from the page.
self.addEventListener('install', event => {
// Bypass the waiting lifecycle stage,
// just in case there's an older version of this SW registration.
event.waitUntil(self.skipWaiting());
});
self.addEventListener('activate', event => {
// Take control of all pages under this SW's scope immediately,
// instead of waiting for reload/navigation.
event.waitUntil(self.clients.claim());
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With