sw.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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', function(event) {
  5. var indexPage = new Request('index.html');
  6. event.waitUntil(
  7. fetch(indexPage).then(function(response) {
  8. return caches.open('kutt-offline').then(function(cache) {
  9. console.log('Kutt Cached index page during Install' + response.url);
  10. return cache.put(indexPage, response);
  11. });
  12. }));
  13. });
  14. //If any fetch fails, it will look for the request in the cache and serve it from there first
  15. self.addEventListener('fetch', function(event) {
  16. var updateCache = function(request) {
  17. return caches.open('kutt-offline').then(function(cache) {
  18. return fetch(request).then(function(response) {
  19. console.log('Kutt add page to offline' + response.url)
  20. return cache.put(request, response);
  21. });
  22. });
  23. };
  24. event.waitUntil(updateCache(event.request));
  25. event.respondWith(
  26. fetch(event.request).catch(function(error) {
  27. console.log('Kutt Network request Failed. Serving content from cache: ' + error);
  28. //Check to see if you have it in the cache
  29. //Return response
  30. //If not in the cache, then return error page
  31. return caches.open('kutt-offline').then(function(cache) {
  32. return cache.match(event.request).then(function(matching) {
  33. var report = !matching || matching.status == 404 ? Promise.reject(new Error('no-match')) : matching;
  34. return report
  35. });
  36. });
  37. })
  38. );
  39. })