我的浏览器注册了 service worker 并缓存了 url 但它不能离线工作?
my browser registers the service worker and caches the urls but it doesn't work offline?
这可以在线注册并完美运行。但是当服务器关闭时,当页面刷新时,注册的 serviceworker 不再出现在控制台中,缓存存储中也没有缓存。
if ("serviceWorker" in navigator){
navigator.serviceWorker.register("/sw.js").then(function(registration){
console.log("service worker reg", registration.scope)
}).catch(function(error){
console.log("Error:", error);
})
}
在sw.js
var CACHE_NAME = 'cache-v1';
var urlsToCache = [
'/index.html'
];
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(CACHE_NAME).then(function(cache) {
return cache.addAll(urlsToCache);
})
);
//event.waitUntil(self.skipWaiting());
});
您已将文件正确添加到缓存中,但未按要求返回缓存文件。
您的 sw.js
还应具有以下代码:
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
return fetch(event.request);
}
)
);
});
来自Introduction to service workers.
此外,您应该像往常一样缓存 /
而不是 /index.html
,您不会直接点击 index.html 文件。
您的服务人员离线时不会显示任何 console.log,因为您没有任何 activate
代码。 This article - offline cookbook 对理解细节非常有用。
这可以在线注册并完美运行。但是当服务器关闭时,当页面刷新时,注册的 serviceworker 不再出现在控制台中,缓存存储中也没有缓存。
if ("serviceWorker" in navigator){
navigator.serviceWorker.register("/sw.js").then(function(registration){
console.log("service worker reg", registration.scope)
}).catch(function(error){
console.log("Error:", error);
})
}
在sw.js
var CACHE_NAME = 'cache-v1';
var urlsToCache = [
'/index.html'
];
self.addEventListener('install', function(event) {
event.waitUntil(
caches.open(CACHE_NAME).then(function(cache) {
return cache.addAll(urlsToCache);
})
);
//event.waitUntil(self.skipWaiting());
});
您已将文件正确添加到缓存中,但未按要求返回缓存文件。
您的 sw.js
还应具有以下代码:
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(response) {
// Cache hit - return response
if (response) {
return response;
}
return fetch(event.request);
}
)
);
});
来自Introduction to service workers.
此外,您应该像往常一样缓存 /
而不是 /index.html
,您不会直接点击 index.html 文件。
您的服务人员离线时不会显示任何 console.log,因为您没有任何 activate
代码。 This article - offline cookbook 对理解细节非常有用。