precache.mjs 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. Copyright 2019 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 {logger} from 'workbox-core/_private/logger.mjs';
  8. import {getOrCreatePrecacheController} from './utils/getOrCreatePrecacheController.mjs';
  9. import {precachePlugins} from './utils/precachePlugins.mjs';
  10. import './_version.mjs';
  11. const installListener = (event) => {
  12. const precacheController = getOrCreatePrecacheController();
  13. const plugins = precachePlugins.get();
  14. event.waitUntil(
  15. precacheController.install({event, plugins})
  16. .catch((error) => {
  17. if (process.env.NODE_ENV !== 'production') {
  18. logger.error(`Service worker installation failed. It will ` +
  19. `be retried automatically during the next navigation.`);
  20. }
  21. // Re-throw the error to ensure installation fails.
  22. throw error;
  23. })
  24. );
  25. };
  26. const activateListener = (event) => {
  27. const precacheController = getOrCreatePrecacheController();
  28. const plugins = precachePlugins.get();
  29. event.waitUntil(precacheController.activate({event, plugins}));
  30. };
  31. /**
  32. * Adds items to the precache list, removing any duplicates and
  33. * stores the files in the
  34. * ["precache cache"]{@link module:workbox-core.cacheNames} when the service
  35. * worker installs.
  36. *
  37. * This method can be called multiple times.
  38. *
  39. * Please note: This method **will not** serve any of the cached files for you.
  40. * It only precaches files. To respond to a network request you call
  41. * [addRoute()]{@link module:workbox-precaching.addRoute}.
  42. *
  43. * If you have a single array of files to precache, you can just call
  44. * [precacheAndRoute()]{@link module:workbox-precaching.precacheAndRoute}.
  45. *
  46. * @param {Array<Object|string>} entries Array of entries to precache.
  47. *
  48. * @alias workbox.precaching.precache
  49. */
  50. export const precache = (entries) => {
  51. const precacheController = getOrCreatePrecacheController();
  52. precacheController.addToCacheList(entries);
  53. if (entries.length > 0) {
  54. // NOTE: these listeners will only be added once (even if the `precache()`
  55. // method is called multiple times) because event listeners are implemented
  56. // as a set, where each listener must be unique.
  57. addEventListener('install', installListener);
  58. addEventListener('activate', activateListener);
  59. }
  60. };