我正在尝试使用服务工作者缓存以下2个资源
<link href="https://s3.xxxxx.amazonaws.com/xxbucketxx/example.css" rel="stylesheet" crossorigin="anonymous">
<script src="https://unpkg.com/vue/dist/vue.min.js" crossorigin="anonymous"></script>
第一个资源来自AWS s3。
注册服务工作者后,使用chrome浏览器检查时,两个文件都存在于缓存存储中。
要检查,在注册服务工作者之后,是否在下一个请求中从缓存中提供资源,我正在使用以下代码:
self.addEventListener("fetch", function(event) {
event.respondWith(
caches.match(event.request).then(function(response) {
if(response != undefined){
return response
}
else{
console.log("Fetching outside cache", event.request.url)
if(event.request.url.includes("?cache=true")){
caches.open("my-cache").then(function(cache){
cache.add(event.request.url);
})
}
return fetch(event.request)
}
})
);
});
vue js资源由服务工作者从缓存中提供。但是,再次从s3中获取了s3资源。 我还为s3存储桶提供了以下CORS政策。
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
答案 0 :(得分:1)
类似于Service worker doesn't return file from cache
self.addEventListener("fetch", function(event) {
event.respondWith(
caches.match(event.request,{cacheName:"my-cache",ignoreVary:true}).then(function(response) {
if(response != undefined){
return response
}
else{
console.log("Fetching outside cache", event.request.url)
if(event.request.url.includes("?cache=true")){
caches.open("my-cache").then(function(cache){
cache.add(event.request.url);
})
}
return fetch(event.request)
}
})
);
});
尝试一下。