Phillip Senn
Phillip Senn

Reputation: 47625

Service workers install event not firing

Taking inspiration from Google's page, I pasted this into my website:

var CACHE_NAME = 'my-site-cache-v1';
var urlsToCache = [
  'serviceworker.css'
];

debugger // 1
self.addEventListener('install', function(event) {
   debugger // 2
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then(function(cache) {
        console.log('Opened cache');
        return cache.addAll(urlsToCache);
      })
  );
});

Debugger 1 stops the program flow, but debugger 2 is never reached.

ServiceWorker.css exists.

I'm navigating to the page using the Incognito window with the developer toolbar open.

Upvotes: 2

Views: 1792

Answers (2)

Ivan Stinsky
Ivan Stinsky

Reputation: 121

For those folks who are working with Next.js the complete nano guide:

  1. create sw.js file in /public folder
const cacheName = "my-cool-cache-v1";
const filesToCache = [
  "/",
  // etc
];

const installEvent = () => {
  self.addEventListener("install", (event) => {
    event.waitUntil(
      caches
        .open(cacheName)
        .then((cache) => {
          console.log("caching files");
          cache.addAll(filesToCache);
        })
        .then(() => self.skipWaiting())
    );
  });
};
installEvent();

const activateEvent = () => {
  self.addEventListener("activate", (event) => {
    event.waitUntil(
      caches.keys().then((keyList) => {
        return Promise.all(
          keyList.map((key) => {
            if (key !== cacheName) {
              return caches.delete(key);
            }
          })
        );
      })
    );
    return self.clients.claim();
  });
};
activateEvent();
  1. create register-sw.js in /public folder: (check the Matt Doran answer https://stackoverflow.com/a/61012423/13649814)
if ("serviceWorker" in navigator) {
  window.addEventListener("load", function () {
    navigator.serviceWorker.register("./sw.js").then(
      function (registration) {
        console.log(
          "ServiceWorker registration successful with scope: ",
          registration.scope
        );
      },
      function (err) {
        console.log("ServiceWorker registration failed: ", err);
      }
    );
  });
}

  1. for nextjs 14+ add <Script src="/register-sw.js" /> to the root layout.tsx

Upvotes: 0

Matt Doran
Matt Doran

Reputation: 2153

The code in your snippet above must be loaded in via register. You will need to be developing with https to see this work

if ('serviceWorker' in navigator) {
window.addEventListener('load', function() {
    navigator.serviceWorker.register('./codeWithYourJsAbove.js').then((function(registration) {
        console.log('ServiceWorker registration successful with scope: ', registration.scope);
    }), function(err) {
        console.log('ServiceWorker registration failed: ', err);
    });
});

}

Upvotes: 2

Related Questions