当我测试以下代码并转到 chrome devtools 的缓存存储时,它是空的。它一会儿起作用,一会儿改变cacheName
它就停止了,不确定它是否相关。
if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
navigator.serviceWorker
.register('sw_cached_pages.js')
.then(reg => console.log('Service Worker: Registered (Pages)'))
.catch(err => console.log(`Service Worker: Error: ${err}`));
});
}
这是软件本身:
const cacheName = '00001';
const cacheAssets = [
'accueil.php',
'js/accueil.js',
'inc/Headers.php',
'inc/footer.php'
];
// Call Install Event
self.addEventListener('install', e => {
console.log('Service Worker: Installed');
e.waitUntil(
caches
.open(cacheName)
.then(cache => {
console.log(cache)
console.log('Service Worker: Caching Files', cache);
cache.addAll(cacheAssets);
})
.then(() => self.skipWaiting())
);
});
// Call Activate Event
self.addEventListener('activate', e => {
console.log('Service Worker: Activated');
// Remove unwanted caches
e.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cache => {
if (cache !== cacheName) {
console.log('Service Worker: Clearing Old Cache');
return caches.delete(cache);
}
})
);
})
);
});
// Call Fetch Event
self.addEventListener('fetch', e => {
console.log('Service Worker: Fetching');
e.respondWith(fetch(e.request).catch(() => caches.match(e.request)));
});