14

I have a website and I installed a service worker at the root and even set the scope to '/' as mentioned here: Service worker is caching files but fetch event is never fired

But, the fetch event is not firing. Any help is appreciated.

importScripts('/site/themes/libs/cache-polyfill.js');

self.addEventListener('install', function (e) {
  e.waitUntil(
    caches.open('v1').then(function (cache) {
      return cache.addAll([
        '/',
        '/test-page',
        '/site/themes/css/main.css',
        '/site/themes/js/vendors.min.js',
        '/site/themes/js/app.min.js'
      ]);
    })
  );

  self.skipWaiting()
});

self.addEventListener('fetch', function (event) {
  console.log(event.request.url);
  event.respondWith(
    caches.match(event.request).then(function (response) {
      return response || fetch(event.request);
    })
  );
});

EDIT: I am using statamic for the website.

Raul Lukacs
  • 165
  • 2
  • 8

1 Answers1

8

First of all verify if the register event of service worker was successful. If yes try adding an activate event listener.

self.addEventListener('activate', function(event) {
  console.log('Claiming control');
  return self.clients.claim();
});
pizzaisdavid
  • 455
  • 3
  • 13
  • 6
    Why does this help? – John Moore Jul 21 '22 at 18:35
  • 6
    Yes, the register event was successful. Yes, the activate callback is invoked. But `fetch` still doesn't trigger. – Resigned June 2023 Aug 29 '22 at 04:46
  • Why this works: `When a service worker is initially registered, pages won't use it until they next load. The claim() method causes those pages to be controlled immediately.` - this is an extract from https://developer.mozilla.org/en-US/docs/Web/API/Clients/claim – Ultimacho Mar 10 '23 at 22:45
  • For me, fetch event triggered if I am moving the service worker file in the root directory (`/`) of the project. Previously I was using that inside the `/src/` folder in my Single page (Vue + Vite) application. – Debug Diva Aug 29 '23 at 10:31