我有一个带有HTML,CSS和JS基本'shell'的应用程序.页面的主要内容是通过多个ajax调用加载到API,该API位于我的应用程序运行的另一个URL上.我已经设置了一个服务工作者来缓存应用程序的主要"shell":
var urlsToCache = [
'/',
'styles/main.css',
'scripts/app.js',
'scripts/apiService.js',
'third_party/handlebars.min.js',
'third_party/handlebars-intl.min.js'
];
Run Code Online (Sandbox Code Playgroud)
并在请求时响应缓存版本.我遇到的问题是我的ajax调用的响应也被缓存.我很确定我需要fetch在service-worker 的事件中添加一些代码,这些代码总是从网络中获取它们而不是查看缓存.
这是我的fetch活动:
self.addEventListener('fetch', function (event) {
// ignore anything other than GET requests
var request = event.request;
if (request.method !== 'GET') {
event.respondWith(fetch(request));
return;
}
// handle other requests
event.respondWith(
caches.open(CACHE_NAME).then(function (cache) {
return cache.match(event.request).then(function (response) {
return response || fetch(event.request).then(function (response) {
cache.put(event.request, response.clone());
return response;
});
});
})
);
});
Run Code Online (Sandbox Code Playgroud)
我不确定如何忽略对API的请求.我试过这样做:
if (request.url.indexOf(myAPIUrl !== -1) {
event.respondWith(fetch(request));
return;
}
Run Code Online (Sandbox Code Playgroud)
但根据Chrome开发工具中的网络选项卡,所有这些响应仍然来自服务工作者.
pir*_*lot 16
您不必event.respondWith(fetch(request))用于处理要忽略的请求.如果您在没有调用event.respondWith浏览器的情况下返回,则会为您获取资源.
你可以这样做:
if (request.method !== 'GET') { return; }
if (request.url.indexOf(myAPIUrl) !== -1) { return; }
\\ handle all other requests
event.respondWith(/* return promise here */);
Run Code Online (Sandbox Code Playgroud)
IOW,只要您可以同步确定您不想处理请求,您只需从处理程序返回并让默认请求处理接管即可.看看这个例子.
| 归档时间: |
|
| 查看次数: |
4123 次 |
| 最近记录: |