简体   繁体   中英

Service Worker for Caching Offline files

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM