【发布时间】:2021-03-30 18:49:17
【问题描述】:
我在基于工作箱的服务工作者中为 NavigationRoute 使用 NetworkFirst 策略,以便在用户离线时为导航请求提供缓存响应。
workbox.routing.registerRoute(
new workbox.routing.NavigationRoute(
new workbox.strategies.NetworkFirst({
cacheName: 'static-pages',
}),
),
);
当我导航到一个页面时,导航请求会被缓存,然后我可以在离线时再次访问它。到目前为止一切顺利。
但是,我需要预先缓存 PWA 启动 URL,因此如果用户从任何页面安装 PWA、脱机并尝试打开它,PWA 启动 URL 将被缓存并可用。事实上,这将是 Chrome 91 的可安装提示的要求。
self.addEventListener('activate', (event) => {
event.waitUntil(
caches.open('static-pages').then(cache => {
const startUrl = 'https://my-pwa-start-url...';
return cache.add(startUrl);
})
);
});
这里的问题是startUrl 的请求不是navigation 请求,因此即使它被缓存在static-pages 缓存中,导航到起始 URL 时也不会使用它。
我尝试手动构建导航请求,例如
const startUrlRequest = new Request(startUrl, { mode: 'navigate' });
return cache.add(startUrlRequest);
然后我得到这个错误:
TypeError: Failed to construct 'Request': Cannot construct a Request with a RequestInit whose mode member is set as 'navigate'.
有没有办法在不实际导航到页面的情况下预先缓存 NavigationRequest?
【问题讨论】:
标签: workbox