sw.js 1.1 KB

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