69 lines
1.5 KiB
JavaScript
69 lines
1.5 KiB
JavaScript
const CACHE_VERSION = 'v1';
|
|
const CACHE_NAME = `portfolio-cache-${CACHE_VERSION}`;
|
|
|
|
const URLS_TO_CACHE = [
|
|
'/',
|
|
'/index.html',
|
|
'/manifest.json'
|
|
];
|
|
|
|
self.addEventListener('install', (event) => {
|
|
event.waitUntil(
|
|
caches.open(CACHE_NAME).then((cache) => {
|
|
return cache.addAll(URLS_TO_CACHE);
|
|
})
|
|
);
|
|
self.skipWaiting();
|
|
});
|
|
|
|
self.addEventListener('activate', (event) => {
|
|
event.waitUntil(
|
|
caches.keys().then((cacheNames) => {
|
|
return Promise.all(
|
|
cacheNames
|
|
.filter((cacheName) => cacheName !== CACHE_NAME)
|
|
.map((cacheName) => caches.delete(cacheName))
|
|
);
|
|
})
|
|
);
|
|
self.clients.claim();
|
|
});
|
|
|
|
self.addEventListener('fetch', (event) => {
|
|
const { request } = event;
|
|
const url = new URL(request.url);
|
|
|
|
if (request.method !== 'GET') {
|
|
return;
|
|
}
|
|
|
|
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
|
return;
|
|
}
|
|
|
|
event.respondWith(
|
|
caches.match(request).then((cachedResponse) => {
|
|
if (cachedResponse) {
|
|
return cachedResponse;
|
|
}
|
|
|
|
return fetch(request)
|
|
.then((response) => {
|
|
if (!response || response.status !== 200 || response.type === 'error') {
|
|
return response;
|
|
}
|
|
|
|
const responseToCache = response.clone();
|
|
caches.open(CACHE_NAME).then((cache) => {
|
|
cache.put(request, responseToCache);
|
|
});
|
|
|
|
return response;
|
|
})
|
|
.catch(() => {
|
|
return caches.match('/index.html');
|
|
});
|
|
})
|
|
);
|
|
});
|