googleFontsCache.js 2.1 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 { registerRoute } from 'workbox-routing/registerRoute.js';
  8. import { StaleWhileRevalidate } from 'workbox-strategies/StaleWhileRevalidate.js';
  9. import { CacheFirst } from 'workbox-strategies/CacheFirst.js';
  10. import { CacheableResponsePlugin } from 'workbox-cacheable-response/CacheableResponsePlugin.js';
  11. import { ExpirationPlugin } from 'workbox-expiration/ExpirationPlugin.js';
  12. import './_version.js';
  13. /**
  14. * An implementation of the [Google fonts]{@link https://developers.google.com/web/tools/workbox/guides/common-recipes#google_fonts} caching recipe
  15. *
  16. * @memberof workbox-recipes
  17. *
  18. * @param {Object} [options]
  19. * @param {string} [options.cachePrefix] Cache prefix for caching stylesheets and webfonts. Defaults to google-fonts
  20. * @param {number} [options.maxAgeSeconds] Maximum age, in seconds, that font entries will be cached for. Defaults to 1 year
  21. * @param {number} [options.maxEntries] Maximum number of fonts that will be cached. Defaults to 30
  22. */
  23. function googleFontsCache(options = {}) {
  24. const sheetCacheName = `${options.cachePrefix || 'google-fonts'}-stylesheets`;
  25. const fontCacheName = `${options.cachePrefix || 'google-fonts'}-webfonts`;
  26. const maxAgeSeconds = options.maxAgeSeconds || 60 * 60 * 24 * 365;
  27. const maxEntries = options.maxEntries || 30;
  28. // Cache the Google Fonts stylesheets with a stale-while-revalidate strategy.
  29. registerRoute(({ url }) => url.origin === 'https://fonts.googleapis.com', new StaleWhileRevalidate({
  30. cacheName: sheetCacheName,
  31. }));
  32. // Cache the underlying font files with a cache-first strategy for 1 year.
  33. registerRoute(({ url }) => url.origin === 'https://fonts.gstatic.com', new CacheFirst({
  34. cacheName: fontCacheName,
  35. plugins: [
  36. new CacheableResponsePlugin({
  37. statuses: [0, 200],
  38. }),
  39. new ExpirationPlugin({
  40. maxAgeSeconds,
  41. maxEntries,
  42. }),
  43. ],
  44. }));
  45. }
  46. export { googleFontsCache };