pwabuilder-sw.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // This is the "Offline page" service worker
  2. importScripts('https://storage.googleapis.com/workbox-cdn/releases/5.1.2/workbox-sw.js');
  3. const CACHE = "pwabuilder-page";
  4. // TODO: replace the following with the correct offline fallback page i.e.: const offlineFallbackPage = "offline.html";
  5. const offlineFallbackPage = "index.html";
  6. self.addEventListener("message", (event) => {
  7. if (event.data && event.data.type === "SKIP_WAITING") {
  8. self.skipWaiting();
  9. }
  10. });
  11. self.addEventListener('install', async (event) => {
  12. event.waitUntil(
  13. caches.open(CACHE)
  14. .then((cache) => cache.add(offlineFallbackPage))
  15. );
  16. });
  17. if (workbox.navigationPreload.isSupported()) {
  18. workbox.navigationPreload.enable();
  19. }
  20. self.addEventListener('fetch', (event) => {
  21. if (event.request.mode === 'navigate') {
  22. event.respondWith((async () => {
  23. try {
  24. const preloadResp = await event.preloadResponse;
  25. if (preloadResp) {
  26. return preloadResp;
  27. }
  28. const networkResp = await fetch(event.request);
  29. return networkResp;
  30. } catch (error) {
  31. const cache = await caches.open(CACHE);
  32. const cachedResp = await cache.match(offlineFallbackPage);
  33. return cachedResp;
  34. }
  35. })());
  36. }
  37. });