![](/img/trans.png)
[英]How to make the Service Worker cache data from API and update the cache when needed
[英]Service Worker serve URL from cache first and update if needed
我首先看到总是带有静态资产的缓存,以便首先离线创建PWA。 但是,是否可以缓存URL并在下一次渲染时首先从缓存中提供它并在需要时更新缓存?
现在在我的PWA上,我复制所有查看的URL,但是我不能先提供缓存:/
我的提取事件:
self.addEventListener("fetch", event => {
const updateCache = request => {
return caches
.open(CACHE_NAME)
.then(cache => {
return fetch(request)
.then(response => {
console.log(`[PWA] add page to offline ${response.url}`);
return cache.put(request, response);
})
.catch(error => console.log(error));
})
.catch(error => console.log(error));
};
event.waitUntil(updateCache(event.request));
event.respondWith(
fetch(event.request).catch(error => {
console.log(
`[PWA] Network request Failed. Serving content from cache: ${error}`
);
// Check to see if you have it in the cache
// Return response
// If not in the cache, then return error page
return caches
.open(CACHE_NAME)
.then(cache => {
return cache.match(event.request).then(matching => {
const report =
!matching || matching.status == 404
? Promise.reject("no-match")
: matching;
return report;
});
})
.catch(error => console.log(error));
})
);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.