1
votes

I'm developing a progressive web application with the intention of caching all assets to be used offline. Here's my service worker

    self.addEventListener('install', function(e) {
        e.waitUntil(
           caches.open('default-cache').then(function(cache) {
              return cache.addAll([
                 '/',
                 '/index.html',
                 '/bundle.js',
                 '/libraries/p5.dom.min.js',
                 '/libraries/p5.min.js',
                 '/libraries/p5.sound.min.js',
                 '/sound/spokesm4v.mp3',
                 '/css/flexboxgrid.min.css',
                 '/images/icon-192.png',
                 '/manifest.json',
            ])
        }).then(function() {
            return self.skipWaiting();
        }));
    });

    self.addEventListener('activate', function(e) {
        e.waitUntil(self.clients.claim());
    });

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

Regardless if I'm online or not, the service worker fails to cache some assets (in this case bundle.js) and breaks my cache-first system, even though I log a success message upon registering the worker.

https://postimg.org/gallery/2yo1ig35y/

2
Like justmarkup, I am not getting any error :( However you are missing a semicolon after returning cache.addAll. Also, service worker registration and installation are separate, so the successful registration message does not mean the service worker installed & cached resources. Just FYI. - David Scales
Which browsers are you testing on? - Salva
I am testing on desktop and mobile chrome - Andrew Eames

2 Answers

1
votes

I don't see the problem that caching fails for bundle.js but when opening coloursel.io I can see in the console that there is a JavaScript error in your sw.js "Uncaught ReferenceError: event is not defined at sw.js:27"

If you change

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

to

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

the Service Worker should work as expected.

0
votes