cachingservice-worker

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.


Solution

  • 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);
        });
    });
    

    }