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