2

We want to make a website available offline, we started with App Cache but found this has been discontinued with Service Worker.

I found some help on setting up a service worker on a test site I created however it still does not seem to work. It registers the service worker etc but doesn't seem to cache anything.

Here is they code for the service worker js. Any ideas?

screenshot of js code 1

dimay
  • 2,768
  • 1
  • 13
  • 22
  • You're only caching one file - your logo. You need a big list of all the files that are referenced by your website. Look in the Chrome Developer Tools Network tab to see all the files being loaded. Those should all be in your cache.addAll list. If you have a manifest.appcache file, that list is a good starting point. – Debbie A Jan 26 '21 at 02:19

1 Answers1

1

Try this:

  1. Load the Service Worker page.

    if(navigator.serviceWorker){
       window.addEventListener('load',() => {
         navigator.serviceWorker
         .register('/sw.js')
         .then(console.log('[ServiceWorker] Registered Successfully'))
         .catch(err => console.log(`[ServiceWorker] Error: ${err}`));
        });
    } else {
        console.log('Service Worker not supported.');
    }
    
  2. In sw.js, add a version.

    const cacheName='cache-2020.10.06-01';
    
  3. In sw.js, added the fetch event.

    self.addEventListener('fetch', (event) => {
      event.respondWith(async function() {
    
        const cache = await caches.open(cacheName);
        const cachedResponse = await cache.match(event.request);
        const networkResponsePromise = fetch(event.request);
    
        event.waitUntil(async function() {
          const networkResponse = await networkResponsePromise;
          await cache.put(event.request, networkResponse.clone());
        }());
    
        // Returned the cached response if we have one, otherwise return the network response.
        return cachedResponse || networkResponsePromise;
      }());
    });
    

This should do basically what you are asking for. Personally I'm trying to take it further by getting it to display an offline page if what I'm requesting isn't already cached and there is no network access. But so far all the examples I've tried that are supposed to demonstrate that feature fail. I think something in the API may have changed since those examples where written.

GL

Vince
  • 910
  • 2
  • 13
  • 29
  • hello, I'm struggling trying to do something you was trying to do : getting and offline page AND some caching while online ... But can't find a way ... Did you succeed ? – Seba99 Feb 23 '21 at 15:03
  • Hi @Seba99 yes, I managed to get offline and caching working properly. This post might help you: [link](https://stackoverflow.com/a/64314859/2327645) – Vince Feb 24 '21 at 18:21