Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Service Worker to intercept requests on the first load of my site?

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?

like image 928
owencm Avatar asked Jan 08 '16 16:01

owencm


People also ask

What are service workers used for?

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.

Can service worker send HTTP request?

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.

Can service workers access cache?

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).


1 Answers

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());
});
like image 134
owencm Avatar answered Oct 06 '22 08:10

owencm