Service Worker 将不会安装并保持其状态为冗余。刷新页面将添加更多处于冗余状态的 Service Worker(灰色指示器)。
我在 self.addEventListener 函数参数中尝试了 console.log("installed") 并且它有效。 Service Worker 被标记为已激活并正在运行(绿色指示器)
下面会让serviceworker变得多余
self.addEventListener("install", function (event) {
event.waitUntil(
caches.open(CACHE_NAME).then(function (cache) {
var newImmutableRequests = [];
return Promise.all(
immutableRequests.map(function (url) {
return caches.match(url).then(function (response) {
if (response) {
return cache.put(url, response);
} else {
newImmutableRequests.push(url);
return Promise.resolve();
}
});
})
).then(function () {
return cache.addAll(newImmutableRequests.concat(mutableRequests));
});
})
);
});
下面可以工作,但它不会缓存文件
self.addEventListener("install", function (event) {
console.log("installed");
});
我希望安装 Service Worker 并能够缓存文件,但它会进入冗余状态。
最佳答案
检查控制台是否有错误。如果失败,Service Worker 将进入“冗余”状态。
您的代码中至少存在一个问题:
return caches.match(url).then(function (response) {
应该是没有s
的缓存
,对吧? caches
是全局 Cache API 接口(interface),而代码中的 cache
是引用单个缓存实例的变量。
此外,为了更轻松地查找代码中的错误,请考虑添加错误处理。您的代码中没有任何 Promise.catch 处理程序,因此它只是吞掉所有错误:)
关于javascript - Service Worker 标记为冗余,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56931513/