pageCache.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  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 { warmStrategyCache } from './warmStrategyCache';
  8. import { registerRoute } from 'workbox-routing/registerRoute.js';
  9. import { NetworkFirst } from 'workbox-strategies/NetworkFirst.js';
  10. import { CacheableResponsePlugin } from 'workbox-cacheable-response/CacheableResponsePlugin.js';
  11. import './_version.js';
  12. /**
  13. * An implementation of a page caching recipe with a network timeout
  14. *
  15. * @memberof workbox-recipes
  16. *
  17. * @param {Object} [options]
  18. * @param {string} [options.cacheName] Name for cache. Defaults to pages
  19. * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.mode === 'navigate';
  20. * @param {number} [options.networkTimoutSeconds] Maximum amount of time, in seconds, to wait on the network before falling back to cache. Defaults to 3
  21. * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe
  22. * @param {string[]} [options.warmCache] Paths to call to use to warm this cache
  23. */
  24. function pageCache(options = {}) {
  25. const defaultMatchCallback = ({ request }) => request.mode === 'navigate';
  26. const cacheName = options.cacheName || 'pages';
  27. const matchCallback = options.matchCallback || defaultMatchCallback;
  28. const networkTimeoutSeconds = options.networkTimeoutSeconds || 3;
  29. const plugins = options.plugins || [];
  30. plugins.push(new CacheableResponsePlugin({
  31. statuses: [0, 200],
  32. }));
  33. const strategy = new NetworkFirst({
  34. networkTimeoutSeconds,
  35. cacheName,
  36. plugins,
  37. });
  38. // Registers the route
  39. registerRoute(matchCallback, strategy);
  40. // Warms the cache
  41. if (options.warmCache) {
  42. warmStrategyCache({ urls: options.warmCache, strategy });
  43. }
  44. }
  45. export { pageCache };