我有一个用香草js编写的SPA,它可以处理带有前缀-/ mail的路由,我想在此处缓存应用程序外壳并将其用于所有子路由,例如/ mail / settings,/ mail / inbox ...等,登录后,此SPA由app.html提供。所以我在用这个-
//this has to be precached for the below createHandlerBoundToURL
workbox.precaching.precacheAndRoute([{
url:"/mail"
}
])
var pagesRouteHandler = workbox.precaching.createHandlerBoundToURL('/mail');
//I need this for dynamic url caching,
var navigationRoutes = new workbox.routing.NavigationRoute(pagesRouteHandler, {
allowlist: [
new RegExp('/mail/*'),
],
});
workbox.routing.registerRoute(navigationRoutes);
当我登录后注册服务工作者时,此方法工作正常。[navigator.serviceWorker.register('/sw.js');
)
但是现在,我也想缓存登录/注册屏幕,它们是单独的html文件,即SPA之外。当我在这些html文件中注册服务工作者时,上面的代码尝试通过发出get请求来预缓存/mail
路由。但是响应将是服务器在没有服务器会话的情况下重定向到登录页面,因此相同的login.html
将被预先缓存为/mail
路由,而不是实际的SPA shell(html)。
因此,我想在登录后或正确注册/ mail路由后(例如在注册/mail
路由的回调中)注册上述/ mail和动态路由。我该怎么做?
注意:没有用户会话,我无法将app.html从服务器发送到/mail
(作为应用程序外壳),因为它是使用用户值呈现的模板。
我通过以下方法解决了这个问题,我没有预先缓存根路径,而是将其缓存为普通路由,
workbox.routing.registerRoute("/mail",new workbox.strategies.StaleWhileRevalidate({
cacheName: "appShell",
}));
并且对于所有子路由(由于它们是由前端本身处理的,并且需要相同的“ / mail”应用程序外壳程序,我正在注册要从缓存处理的RegExp路由。
workbox.routing.registerRoute(({ url, event }) => {
return new RegExp(/(\/mail\/.*)/).test(url.pathname);
}, ({ url, event, params }) => {
if (event.request.mode === "navigate") {
// Always respond to navigations with the cached /mail, regardless of the underlying event.request.url value.
event.respondWith(caches.match("/mail"));//cache.match(...) is a promise
}
};);
虽然这对我有用,但我希望有一个更明智,更好的解决方案,可能是一些库内置的功能。