当网络响应为404时,将Workbox配置为使用缓存响应

时间:2018-06-08 13:54:30

标签: service-worker workbox

此问题原来是asked in a tweet

当网络响应的HTTP状态为404时,是否有办法配置Workbox以响应缓存响应?

1 个答案:

答案 0 :(得分:1)

是的,您可以创建自己的自定义handlerCallback来完成该操作。部分详细信息会因您的具体设置(缓存名称,后备网址等)而异,以及您是否要使用正式的工作箱策略(例如// Assume that this URL is already cached somewhere, e.g. precached. const fallbackUrl = '/404-fallback.html'; const notFoundFallbackHandler = async ({event}) => { const fetchResponse = await fetch(event.request); if (fetchResponse.status === 404) { return caches.match(fallbackUrl); } else { return fetchResponse; } }; // To apply this handler based on a URL pattern: workbox.routing.registerRoute( new RegExp('/some/criteria/to/match'), notFoundFallbackHandler ); // Or, to apply this handler for all navigation requests, use this: // const navigationRoute = new workbox.routing.NavigationRoute(notFoundFallbackHandler); // workbox.routing.registerRoute(navigationRoute); 而不是fn:string-join(/root/attributes[ov='true']/*/Value/string(), ",") ),但一般来说,以下应该有效:

{{1}}