service_worker.js 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // Incrementing OFFLINE_VERSION will kick off the install event and force
  2. // previously cached resources to be updated from the network.
  3. const OFFLINE_VERSION = 1;
  4. const CACHE_NAME = "offline";
  5. self.addEventListener("install", (event) => {
  6. event.waitUntil(
  7. (async () => {
  8. const cache = await caches.open(CACHE_NAME);
  9. // Setting {cache: 'reload'} in the new request will ensure that the
  10. // response isn't fulfilled from the HTTP cache; i.e., it will be from
  11. // the network.
  12. await cache.add(new Request(OFFLINE_URL, { cache: "reload" }));
  13. })()
  14. );
  15. // Force the waiting service worker to become the active service worker.
  16. self.skipWaiting();
  17. });
  18. self.addEventListener("fetch", (event) => {
  19. // We proxify requests through fetch() only if we are offline because it's slower.
  20. if (navigator.onLine === false && event.request.mode === "navigate") {
  21. event.respondWith(
  22. (async () => {
  23. try {
  24. // Always try the network first.
  25. const networkResponse = await fetch(event.request);
  26. return networkResponse;
  27. } catch (error) {
  28. // catch is only triggered if an exception is thrown, which is likely
  29. // due to a network error.
  30. // If fetch() returns a valid HTTP response with a response code in
  31. // the 4xx or 5xx range, the catch() will NOT be called.
  32. const cache = await caches.open(CACHE_NAME);
  33. const cachedResponse = await cache.match(OFFLINE_URL);
  34. return cachedResponse;
  35. }
  36. })()
  37. );
  38. }
  39. });