如何在动态网页中执行 Fetch
How to do a Fetch in a dynamic web page
所以,
我正在开发 PWA,但我正在开发动态应用程序(一页)。这意味着当我尝试对我的服务人员执行 addEventListener(fetch) 时,什么都没有 returns。我尝试手动获取,例如获取我的本地主机等...它运行良好,但我无法访问 fetch.request!因此,如果我无法通过提取访问缓存数据,我真的不知道如何对我的应用程序执行离线操作。
这是我已经尝试过但没有收到任何提取事件的方法:
this.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).catch(function() {
return fetch(event.request).then(function(response) {
return caches.open('v2').then(function(cache) {
cache.put(event.request, response.clone());
return response;
});
});
})
);
});
有什么想法吗?
如果您想在 fetch
处理程序中遵循应用程序 Shell/single-page 应用程序路由模型,最好的方法是检查 event.request.mode === 'navigate'
在您的 fetch
处理程序。如果是,则意味着用户已导航至 some URL,并且您可能已经拥有一个通用的 URLs shell.html
已缓存,可用于满足该导航请求。
this.addEventListener('fetch', function(event) {
if (event.request.mode === 'navigate') {
// This assumes that shell.html was already cached,
// e.g. as part of your `install` handler.
event.respondWith(caches.match('shell.html'));
return;
}
// Your other response/caching logic goes here.
});
所以,
我正在开发 PWA,但我正在开发动态应用程序(一页)。这意味着当我尝试对我的服务人员执行 addEventListener(fetch) 时,什么都没有 returns。我尝试手动获取,例如获取我的本地主机等...它运行良好,但我无法访问 fetch.request!因此,如果我无法通过提取访问缓存数据,我真的不知道如何对我的应用程序执行离线操作。
这是我已经尝试过但没有收到任何提取事件的方法:
this.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request).catch(function() {
return fetch(event.request).then(function(response) {
return caches.open('v2').then(function(cache) {
cache.put(event.request, response.clone());
return response;
});
});
})
);
});
有什么想法吗?
如果您想在 fetch
处理程序中遵循应用程序 Shell/single-page 应用程序路由模型,最好的方法是检查 event.request.mode === 'navigate'
在您的 fetch
处理程序。如果是,则意味着用户已导航至 some URL,并且您可能已经拥有一个通用的 URLs shell.html
已缓存,可用于满足该导航请求。
this.addEventListener('fetch', function(event) {
if (event.request.mode === 'navigate') {
// This assumes that shell.html was already cached,
// e.g. as part of your `install` handler.
event.respondWith(caches.match('shell.html'));
return;
}
// Your other response/caching logic goes here.
});