PrecacheFallbackPlugin.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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 { getOrCreatePrecacheController } from './utils/getOrCreatePrecacheController.js';
  8. import './_version.js';
  9. /**
  10. * `PrecacheFallbackPlugin` allows you to specify an "offline fallback"
  11. * response to be used when a given strategy is unable to generate a response.
  12. *
  13. * It does this by intercepting the `handlerDidError` plugin callback
  14. * and returning a precached response, taking the expected revision parameter
  15. * into account automatically.
  16. *
  17. * Unless you explicitly pass in a `PrecacheController` instance to the
  18. * constructor, the default instance will be used. Generally speaking, most
  19. * developers will end up using the default.
  20. *
  21. * @memberof workbox-precaching
  22. */
  23. class PrecacheFallbackPlugin {
  24. /**
  25. * Constructs a new PrecacheFallbackPlugin with the associated fallbackURL.
  26. *
  27. * @param {Object} config
  28. * @param {string} config.fallbackURL A precached URL to use as the fallback
  29. * if the associated strategy can't generate a response.
  30. * @param {PrecacheController} [config.precacheController] An optional
  31. * PrecacheController instance. If not provided, the default
  32. * PrecacheController will be used.
  33. */
  34. constructor({ fallbackURL, precacheController, }) {
  35. /**
  36. * @return {Promise<Response>} The precache response for the fallback URL.
  37. *
  38. * @private
  39. */
  40. this.handlerDidError = () => this._precacheController.matchPrecache(this._fallbackURL);
  41. this._fallbackURL = fallbackURL;
  42. this._precacheController =
  43. precacheController || getOrCreatePrecacheController();
  44. }
  45. }
  46. export { PrecacheFallbackPlugin };