reactjs - Create React App v4 生成的 PWA 中的 API 缓存
问题描述
这是使用的模板cra-template-pwa-typescript
。如何缓存外部 API 和图像?
解决方案
c-r-a
v4 使用一个模型,在该模型中,您可以完全控制由 Workbox 提供支持的 Service Worker 文件。
Workbox 文档中有关缓存的一般指南应该会有所帮助:https ://developers.google.com/web/tools/workbox/guides/handle-third-party-requests
举一个具体的例子,假设您想使用 stale-while-revalidate 策略缓存所有跨域图像。您可以通过将此路由添加到您的服务工作人员文件来做到这一点:
registerRoute(
({request, url}) => url.origin !== self.location.origin &&
request.destination === 'image',
new StaleWhileRevalidate({
cacheName: 'cross-origin-images',
plugins: [
// Ensure that once this runtime cache reaches a maximum size the
// least-recently used images are removed.
new ExpirationPlugin({ maxEntries: 50 }),
],
})
);
推荐阅读
- excel - 具有更多结果的 VBA 循环
- java - 一种方法中的多个布尔测试
- ios - 如何更改模态演示ios13的背景颜色?
- android - 启动 AVD Android 10.0 API 29 时 Windows 10 蓝屏死机
- python - 如何从python字符串中提取日期
- azure - 如何在应用服务计划中的应用之间分配资源
- python - 多类分割 UNet 给出了意想不到的输出
- r - 我可以使用 lm 的多个子集创建一个带有 geom_smooth 的 lm 吗?
- c - 我没有得到此代码的输出(反转字符串)。谁能告诉我为什么?
- android - 如何防止 gms.Task 的内存泄漏?