48 lines
1.1 KiB
JavaScript
Executable File
48 lines
1.1 KiB
JavaScript
Executable File
// Service Worker for InfoGenie App
|
|
const CACHE_NAME = 'infogenie-cache-v1';
|
|
const urlsToCache = [
|
|
'/',
|
|
'/index.html',
|
|
'/manifest.json'
|
|
];
|
|
|
|
// 安装Service Worker
|
|
self.addEventListener('install', event => {
|
|
event.waitUntil(
|
|
caches.open(CACHE_NAME)
|
|
.then(cache => {
|
|
console.log('Opened cache');
|
|
return cache.addAll(urlsToCache);
|
|
})
|
|
);
|
|
});
|
|
|
|
// 拦截请求并从缓存中响应
|
|
self.addEventListener('fetch', event => {
|
|
event.respondWith(
|
|
caches.match(event.request)
|
|
.then(response => {
|
|
// 如果找到缓存的响应,则返回缓存
|
|
if (response) {
|
|
return response;
|
|
}
|
|
return fetch(event.request);
|
|
})
|
|
);
|
|
});
|
|
|
|
// 更新Service Worker
|
|
self.addEventListener('activate', event => {
|
|
const cacheWhitelist = [CACHE_NAME];
|
|
event.waitUntil(
|
|
caches.keys().then(cacheNames => {
|
|
return Promise.all(
|
|
cacheNames.map(cacheName => {
|
|
if (cacheWhitelist.indexOf(cacheName) === -1) {
|
|
return caches.delete(cacheName);
|
|
}
|
|
})
|
|
);
|
|
})
|
|
);
|
|
}); |