这是我的sw.js(service worker.js)
self.addEventListener('install', function (event) {
console.log('SW Installed');
event.waitUntil(
caches.open('static')
.then(function (cache) {
// cache.add('/');
// cache.add('/index.html');
// cache.add('/src/js/app.js');
cache.addAll([
"index.html",
"style.css",
"bootstrap.min.js",
"bootstrap.min.css",
"images/icon.png",
"images/golden.jpg",
"images/golden1.jpg",
"images/golden2.jpg",
"images/golden3.jpg",
"images/golden4.jpg",
"images/golden5.jpg",
]);
})
);
});
self.addEventListener('activate', function () {
console.log('SW Activated');
});
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request)
.then(function(res) {
if (res) {
return res;
} else {
return fetch(event.request);
}
})
);
});
这是我的app.js
if('serviceWorker' in navigator){
window.onload = () => {
navigator.serviceWorker.register('sw.js')
.then(function (argument) {
// body...
console.log('serviceWorker registered');
});
};
}
as you can see the cache file is there when the app is online
but as soon as its offline the cache file gets deleted
请帮助,我让缓存在浏览器中存储了一段时间,然后再次打开它以检查服务工作者是否正在工作。它正在工作,但是一旦我下线,服务人员和缓存都将被删除,浏览器将显示您处于离线状态。
答案 0 :(得分:0)
您可以尝试将根路径添加到缓存:
cache.addAll([
"/",
"index.html",
"style.css",
...
]);