offlineFallback.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. /*
  2. Copyright 2020 Google LLC
  3. Use of this source code is governed by an MIT-style
  4. license that can be found in the LICENSE file or at
  5. https://opensource.org/licenses/MIT.
  6. */
  7. import { setCatchHandler } from 'workbox-routing/setCatchHandler.js';
  8. import { matchPrecache } from 'workbox-precaching/matchPrecache.js';
  9. import './_version.js';
  10. /**
  11. * An implementation of the [comprehensive fallbacks recipe]{@link https://developers.google.com/web/tools/workbox/guides/advanced-recipes#comprehensive_fallbacks}. Be sure to include the fallbacks in your precache injection
  12. *
  13. * @memberof workbox-recipes
  14. *
  15. * @param {Object} [options]
  16. * @param {string} [options.pageFallback] Precache name to match for pag fallbacks. Defaults to offline.html
  17. * @param {string} [options.imageFallback] Precache name to match for image fallbacks.
  18. * @param {string} [options.fontFallback] Precache name to match for font fallbacks.
  19. */
  20. function offlineFallback(options = {}) {
  21. const pageFallback = options.pageFallback || 'offline.html';
  22. const imageFallback = options.imageFallback || false;
  23. const fontFallback = options.fontFallback || false;
  24. self.addEventListener('install', (event) => {
  25. const files = [pageFallback];
  26. if (imageFallback) {
  27. files.push(imageFallback);
  28. }
  29. if (fontFallback) {
  30. files.push(fontFallback);
  31. }
  32. event.waitUntil(self.caches
  33. .open('workbox-offline-fallbacks')
  34. .then((cache) => cache.addAll(files)));
  35. });
  36. const handler = async (options) => {
  37. const dest = options.request.destination;
  38. const cache = await self.caches.open('workbox-offline-fallbacks');
  39. if (dest === 'document') {
  40. const match = (await matchPrecache(pageFallback)) ||
  41. (await cache.match(pageFallback));
  42. return match || Response.error();
  43. }
  44. if (dest === 'image' && imageFallback !== false) {
  45. const match = (await matchPrecache(imageFallback)) ||
  46. (await cache.match(imageFallback));
  47. return match || Response.error();
  48. }
  49. if (dest === 'font' && fontFallback !== false) {
  50. const match = (await matchPrecache(fontFallback)) ||
  51. (await cache.match(fontFallback));
  52. return match || Response.error();
  53. }
  54. return Response.error();
  55. };
  56. setCatchHandler(handler);
  57. }
  58. export { offlineFallback };