sw.js 1.1 KB

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