【发布时间】:2019-01-10 01:41:58
【问题描述】:
启用我的应用程序离线运行。在安装过程中,服务人员应该:
- 从异步 API 获取 URL 列表
- 重新格式化响应
- 将响应中的所有 URL 添加到预缓存中
对于这项任务,我将 Google 的 Workbox 与 Webpack 结合使用。
问题:虽然服务工作者成功缓存了所有 Webpack 资产(这告诉我工作箱基本上做了它应该做的),但它并没有等待异步 API 调用来缓存额外的远程资产。它们被简单地忽略,既不缓存也不在网络中获取。
这是我的服务工作者代码:
importScripts('https://storage.googleapis.com/workbox-cdn/releases/3.1.0/workbox-sw.js');
workbox.skipWaiting();
workbox.clientsClaim();
self.addEventListener('install', (event) => {
const precacheController = new workbox.precaching.PrecacheController();
const preInstallUrl = 'https://www.myapiurl/Assets';
event.waitUntil(fetch(preInstallUrl)
.then(response => response.json()
.then((Assets) => {
Object.keys(Assets.data.Assets).forEach((key) => {
precacheController.addToCacheList([Assets.data.Assets[key]]);
});
})));
});
self.__precacheManifest = [].concat(self.__precacheManifest || []);
workbox.precaching.suppressWarnings();
workbox.precaching.precacheAndRoute(self.__precacheManifest, {});
workbox.routing.registerRoute(/^.*\.(jpg|JPG|gif|GIF|png|PNG|eot|woff(2)?|ttf|svg)$/, workbox.strategies.cacheFirst({ cacheName: 'image-cache', plugins: [new workbox.cacheableResponse.Plugin({ statuses: [0, 200] }), new workbox.expiration.Plugin({ maxEntries: 600 })] }), 'GET');
这是我对工作箱的 webpack 配置:
new InjectManifest({
swDest: 'sw.js',
swSrc: './src/sw.js',
globPatterns: ['dist/*.{js,png,html,css,gif,GIF,PNG,JPG,jpeg,woff,woff2,ttf,svg,eot}'],
maximumFileSizeToCacheInBytes: 5 * 1024 * 1024,
}),
【问题讨论】: