precache.js 2.4 KB

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