此页面包含可以与Workbox一起使用的一组示例缓存策略。
谷歌字体
谷歌字体服务包含两部分
- 具有@font-face的定义的样式表,会链接字体文件
- 静态的修订版的字体文件
样式表可以经常更改,因此最好在重新验证时使用陈旧之类的缓存策略来检查每个请求的更新。另一方面,字体文件本身不会更改,可以利用缓存优先策略。
在这里,我们将缓存字体文件的有效期限制为一年(与HTTP Cache-Control标头匹配),最大限制个数为30(以确保我们不会用完用户设备上的过多存储空间)。
import {registerRoute} from 'workbox-routing';
import {CacheFirst, StaleWhileRevalidate} from 'workbox-strategies';
import {CacheableResponsePlugin} from 'workbox-cacheable-response';
import {ExpirationPlugin} from 'workbox-expiration';
// Cache the Google Fonts stylesheets with a stale-while-revalidate strategy.
registerRoute(
({url}) => url.origin === 'https://fonts.googleapis.com',
new StaleWhileRevalidate({
cacheName: 'google-fonts-stylesheets',
})
);
// Cache the underlying font files with a cache-first strategy for 1 year.
registerRoute(
({url}) => url.origin === 'https://fonts.gstatic.com',
new CacheFirst({
cacheName: 'google-fonts-webfonts',
plugins: [
new CacheableResponsePlugin({
statuses: [0, 200],
}),
new ExpirationPlugin({
maxAgeSeconds: 60 * 60 * 24 * 365,
maxEntries: 30,
}),
],
})
);
缓存图片
通过与请求的预期目标进行匹配,您可能希望对图像使用缓存优先策略。
import {registerRoute} from 'workbox-routing';
import {ExpirationPlugin} from 'workbox-expiration';
registerRoute(
({request}) => request.destination === 'image',
new CacheFirst({
cacheName: 'images',
plugins: [
new ExpirationPlugin({
maxEntries: 60,
maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
}),
],
})
);
缓存css和js文件
您可能希望通过与传入请求进行匹配,对未预缓存的CSS和JavaScript文件使用“过时验证”策略。
import {registerRoute} from 'workbox-routing';
import {StaleWhileRevalidate} from 'workbox-strategies';
registerRoute(
({request}) => request.destination === 'script' ||
request.destination === 'style',
new StaleWhileRevalidate({
cacheName: 'static-resources',
})
);
缓存多个源的内容
通过将多个检查组合到单个matchCallback函数中,可以创建正则表达式以在一条路由中缓存来自多个源的相似请求。
import {registerRoute} from 'workbox-routing';
import {StaleWhileRevalidate} from 'workbox-strategies';
registerRoute(
({url}) => url.origin === 'https://fonts.googleapis.com' ||
url.origin === 'https://fonts.gstatic.com',
new StaleWhileRevalidate(),
);
限制特定源的缓存
您可以缓存特定来源的静态资源,并在该缓存上应用到期规则。例如,下面的示例最多缓存50个请求,缓存有效期5分钟。
import {registerRoute} from 'workbox-routing';
import {CacheFirst} from 'workbox-strategies';
import {CacheableResponsePlugin} from 'workbox-cacheable-response';
import {ExpirationPlugin} from 'workbox-expiration';
registerRoute(
({url}) => url.origin === 'https://hacker-news.firebaseio.com',
new CacheFirst({
cacheName: 'stories',
plugins: [
new ExpirationPlugin({
maxEntries: 50,
maxAgeSeconds: 5 * 60, // 5 minutes
}),
new CacheableResponsePlugin({
statuses: [0, 200],
}),
],
})
);
对于网络请求强制一个超时时间
可能存在一些网络请求,如果直接是通过网络提供服务,则可能会比较好,但如果网络请求的时间过长,则可以通过缓存提供服务会比较好。
为此,可以使用配置了networkTimeoutSeconds选项的NetworkFirst策略。
import {registerRoute} from 'workbox-routing';
import {NetworkFirst} from 'workbox-strategies';
import {ExpirationPlugin} from 'workbox-expiration';
registerRoute(
({url}) => url.origin === 'https://hacker-news.firebaseio.com',
new NetworkFirst({
networkTimeoutSeconds: 3,
cacheName: 'stories',
plugins: [
new ExpirationPlugin({
maxEntries: 50,
maxAgeSeconds: 5 * 60, // 5 minutes
}),
],
})
);
从一个特定的子目录缓存资源
您可以通过检查传递给matchCallback函数的URL对象的origin和pathname属性,将请求路由到本地Web应用程序中特定目录中的文件:
import {registerRoute} from 'workbox-routing';
import {StaleWhileRevalidate} from 'workbox-strategies';
registerRoute(
({url}) => url.origin === self.location.origin &&
url.pathname.startsWith('/static/'),
new StaleWhileRevalidate()
);
根据资源类型缓存资源
您可以使用请求目标的枚举类型来确定策略。例如,当目标是数据时:
import {registerRoute} from 'workbox-routing';
import {CacheFirst} from 'workbox-strategies';
import {ExpirationPlugin} from 'workbox-expiration';
registerRoute(
// Custom `matchCallback` function
({request}) => request.destination === 'audio',
new CacheFirst({
cacheName: 'audio',
plugins: [
new ExpirationPlugin({
maxEntries: 60,
maxAgeSeconds: 30 * 24 * 60 * 60, // 30 Days
}),
],
})
);
在你的web app的代码中访问缓存
Cache Storage API 可用于 service worker和window客户端的上下文。如果要从Web应用程序的上下文中更改缓存(添加或删除条目,或获取缓存的URL列表),则可以直接执行此操作,而无需通过postMessage()与 service worker进行通信。
例如,如果您想将URL添加到给定的缓存中以响应Web应用程序中的用户操作,则可以使用如下代码:
// Inside app.js:
async function addToCache(urls) {
const myCache = await window.caches.open('my-cache');
await myCache.addAll(urls);
}
// Call addToCache whenever you'd like. E.g. to add to cache after a page load:
window.addEventListener('load', () => {
// ...determine the list of related URLs for the current page...
addToCache(['/static/relatedUrl1', '/static/relatedUrl2']);
});
然后,在service worker中设置路由时可以引用缓存名称“ my-cache”,并且该路由可以使用网页本身已经添加的任何缓存条目:
// Inside service-worker.js:
import {registerRoute} from 'workbox-routing';
import {StaleWhileRevalidate} from 'workbox-strategies';
registerRoute(
({url}) => url.origin === self.location.origin &&
url.pathname.startsWith('/static/'),
new StaleWhileRevalidate({
cacheName: 'my-cache', // Use the same cache name as before.
})
);