Javascript 如果动态缓存中不存在静态页面,如何在PWA中加载该页面
我的PWA使用web优先缓存策略 如果请求成功,它将以url作为键存储在动态缓存中 如果请求失败,服务工作者将查看该请求是否存储在动态缓存中并返回它 这部分工作正常,我可以在离线时访问所有我在线访问过的页面,问题是我想返回静态html页面,带有一个按钮,当动态缓存中没有任何内容时,该按钮将指向主页 我之所以想这么做,是因为如果我试图访问尚未动态缓存的页面,因为全屏模式下并没有浏览器后退按钮,我会被困在脱机页面上 我的服务人员代码:Javascript 如果动态缓存中不存在静态页面,如何在PWA中加载该页面,javascript,service-worker,progressive-web-apps,Javascript,Service Worker,Progressive Web Apps,我的PWA使用web优先缓存策略 如果请求成功,它将以url作为键存储在动态缓存中 如果请求失败,服务工作者将查看该请求是否存储在动态缓存中并返回它 这部分工作正常,我可以在离线时访问所有我在线访问过的页面,问题是我想返回静态html页面,带有一个按钮,当动态缓存中没有任何内容时,该按钮将指向主页 我之所以想这么做,是因为如果我试图访问尚未动态缓存的页面,因为全屏模式下并没有浏览器后退按钮,我会被困在脱机页面上 我的服务人员代码: event.respondWith( fetch(ev
event.respondWith(
fetch(event.request)
.then(function(res) {
return caches.open('eyewit')
.then(function(cache) {
// console.log( 'Goes to cache: ' + event.request.url );
// console.log( 'DYNAMIC' );
let url = event.request.url;
// dont cache maps
if (url.indexOf('google') == -1) {
// store request to dynamic cache
cache.put(url, res.clone());
}
return res;
})
})
.catch(function(err) {
// look for value in cache if request fails
console.log( 'From cache' );
// I would like to return static page ./offline.html if there is nothing in cache
// with key event.request, if value exist return it instead
// caches.match returns promise
return caches.match(event.request);
})
);
我尝试过这样做,但不起作用,因为caches.matchevent.request返回承诺:
.catch(function(err) {
// return value from dynamic cache if exists
if(caches.match(event.request)) {
return caches.match(event.request);
} else {
// serve static page
return caches.open('static_cache')
.then((cache) => {
return cache.match('offline.html');
});
}
如果caches.match返回承诺,则需要等待响应
.catch(function(err) {
// return value from dynamic cache if exists
return caches.match(event.request).then(function(result) {
// If no match, result will be undefined
if (result) {
return result;
} else {
return caches.open('static_cache')
.then((cache) => {
return cache.match('offline.html');
});
}
});