staticResourceCache.js 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  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 { StaleWhileRevalidate } from 'workbox-strategies/StaleWhileRevalidate.js';
  10. import { CacheableResponsePlugin } from 'workbox-cacheable-response/CacheableResponsePlugin.js';
  11. import './_version.js';
  12. /**
  13. * An implementation of the [CSS and JavaScript files recipe]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#cache_css_and_javascript_files}
  14. *
  15. * @memberof workbox-recipes
  16. *
  17. * @param {Object} [options]
  18. * @param {string} [options.cacheName] Name for cache. Defaults to static-resources
  19. * @param {RouteMatchCallback} [options.matchCallback] Workbox callback function to call to match to. Defaults to request.destination === 'style' || request.destination === 'script' || request.destination === 'worker';
  20. * @param {WorkboxPlugin[]} [options.plugins] Additional plugins to use for this recipe
  21. * @param {string[]} [options.warmCache] Paths to call to use to warm this cache
  22. */
  23. function staticResourceCache(options = {}) {
  24. const defaultMatchCallback = ({ request }) => request.destination === 'style' ||
  25. request.destination === 'script' ||
  26. request.destination === 'worker';
  27. const cacheName = options.cacheName || 'static-resources';
  28. const matchCallback = options.matchCallback || defaultMatchCallback;
  29. const plugins = options.plugins || [];
  30. plugins.push(new CacheableResponsePlugin({
  31. statuses: [0, 200],
  32. }));
  33. const strategy = new StaleWhileRevalidate({
  34. cacheName,
  35. plugins,
  36. });
  37. registerRoute(matchCallback, strategy);
  38. // Warms the cache
  39. if (options.warmCache) {
  40. warmStrategyCache({ urls: options.warmCache, strategy });
  41. }
  42. }
  43. export { staticResourceCache };