Blazor WASM(Hosted)with PWA:如何更改当前的服务工作者代码以使用网络优先策略



当前代码看起来像是先缓存策略,如何修改它先使用网络,然后在网络故障时回退到缓存?

async function onFetch(event) {
let cachedResponse = null;
if (event.request.method === 'GET') {
// For all navigation requests, try to serve index.html from cache
// If you need some URLs to be server-rendered, edit the following check to exclude those URLs
//const shouldServeIndexHtml = event.request.mode === 'navigate';
console.log("onFetch : " + event.request.url.toLowerCase());
const shouldServeIndexHtml = event.request.mode === 'navigate';

const request = shouldServeIndexHtml ? 'index.html' : event.request;
const cache = await caches.open(cacheName);
cachedResponse = await cache.match(request);
}
return cachedResponse || fetch(event.request);
}
if (event.request.url.indexOf('/api') != -1) {
try {
// Network first
var response = await fetch(event.request);
// Update or add cache
await cache.put(event.request, response.clone());
// Change return value
cachedResponse = response;
}
catch (e)
{

}
}

您可以在以下位置添加类似内容:

cachedResponse = await cache.match(request);

这应该总是首先从网络加载api请求,因为它最初不是缓存的一部分。每次为此请求续订缓存时。如果请求失败,将使用缓存的值。

相关内容

  • 没有找到相关文章