Manzana
Manzana

Reputation: 325

Service worker is not caching

When I test the following code and I go to the cache storage of the chrome devtools it is empty. It worked at a moment and after changing the cacheName at a moment it stopped, not sure if it is related.

if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
      navigator.serviceWorker
        .register('sw_cached_pages.js')
        .then(reg => console.log('Service Worker: Registered (Pages)'))
        .catch(err => console.log(`Service Worker: Error: ${err}`));
    });
  }

And here is the SW itself:

const cacheName = '00001';

const cacheAssets = [
  'accueil.php',
  'js/accueil.js',
  'inc/Headers.php',
  'inc/footer.php'
];

// Call Install Event
self.addEventListener('install', e => {
  console.log('Service Worker: Installed');

  e.waitUntil(
    caches
      .open(cacheName)
      .then(cache => {
        console.log(cache)
        console.log('Service Worker: Caching Files', cache);
        cache.addAll(cacheAssets);
      })
      .then(() => self.skipWaiting())
  );
});

// Call Activate Event
self.addEventListener('activate', e => {
  console.log('Service Worker: Activated');
  // Remove unwanted caches
  e.waitUntil(
    caches.keys().then(cacheNames => {
      return Promise.all(
        cacheNames.map(cache => {
          if (cache !== cacheName) {
            console.log('Service Worker: Clearing Old Cache');
            return caches.delete(cache);
          }
        })
      );
    })
  );
});

// Call Fetch Event
self.addEventListener('fetch', e => {
  console.log('Service Worker: Fetching');
  e.respondWith(fetch(e.request).catch(() => caches.match(e.request)));
});

Upvotes: 3

Views: 2944

Answers (2)

warpech
warpech

Reputation: 6433

Maybe the reason is that you have "Disable cache" checked in your browser's DevTools? That was the reason for a similar problem that I had.

Upvotes: 4

lxhom
lxhom

Reputation: 791

So the problem lies in this section:

// Call Install Event
self.addEventListener('install', e => {
  console.log('Service Worker: Installed');

  e.waitUntil(
    caches
      .open(cacheName)
      .then(cache => {
        console.log(cache)
        console.log('Service Worker: Caching Files', cache);
        cache.addAll(cacheAssets); // <- here
      })
      .then(() => self.skipWaiting())
  );
});

It's super simple: cache.addAll returns a promise, and you don't wait for it. You just have to add a return before the cache.addAll statement, that'll pass the promise to the next .then() (.then(() => self.skipWaiting())).

By the way: A better solution would be to use await, because it'd make it more clear. It'd look like this:

e.waitUntil(
  async () => {
    cache = await caches.open(cacheName);
    console.log('Service Worker: Caching Files', cache);
    await cache.addAll(cacheAssets);
    self.skipWaiting();
  }
);

Learning async/await is super helpful and would've made this much easier to debug.

Upvotes: 0

Related Questions