sw.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. // This is the "Offline copy of pages" service worker
  2. // Install stage sets up the index page (home page) in the cache and opens a new cache
  3. const { self } = window;
  4. self.addEventListener('install', event => {
  5. const indexPage = new Request('index.html');
  6. event.waitUntil(
  7. fetch(indexPage).then(response =>
  8. caches.open('kutt-offline').then(cache => cache.put(indexPage, response))
  9. )
  10. );
  11. });
  12. // If any fetch fails, it will look for the request in the cache and serve it from there first
  13. self.addEventListener('fetch', event => {
  14. const updateCache = request =>
  15. caches
  16. .open('kutt-offline')
  17. .then(cache => fetch(request).then(response => cache.put(request, response)));
  18. event.waitUntil(updateCache(event.request));
  19. event.respondWith(
  20. fetch(event.request).catch(() =>
  21. // Check to see if you have it in the cache
  22. // Return response
  23. // If not in the cache, then return error page
  24. caches.open('kutt-offline').then(cache =>
  25. cache.match(event.request).then(matching => {
  26. const report =
  27. !matching || matching.status === 404 ? Promise.reject(new Error('no-match')) : matching;
  28. return report;
  29. })
  30. )
  31. )
  32. );
  33. });