55 lines
1.6 KiB
JavaScript
55 lines
1.6 KiB
JavaScript
const CACHE_NAME = 'mynation-cache-v1';
|
|
const PRECACHE_ASSETS = [
|
|
'./',
|
|
'index.html',
|
|
'css/output.css',
|
|
'js/app.js',
|
|
'manifest.json'
|
|
];
|
|
|
|
self.addEventListener('install', function (event) {
|
|
event.waitUntil(
|
|
Promise.allSettled(
|
|
PRECACHE_ASSETS.map(function (url) {
|
|
return caches.open(CACHE_NAME).then(function (cache) {
|
|
return fetch(url, { cache: 'no-cache' }).then(function (response) {
|
|
if (response.ok) cache.put(url, response.clone());
|
|
return response;
|
|
}).catch(function () {
|
|
return cache.match(url);
|
|
});
|
|
});
|
|
})
|
|
).then(function () { return self.skipWaiting(); })
|
|
);
|
|
});
|
|
|
|
self.addEventListener('fetch', function (event) {
|
|
if (event.request.method !== 'GET') return;
|
|
event.respondWith(
|
|
(async function () {
|
|
try {
|
|
var networkResponse = await fetch(event.request);
|
|
if (networkResponse.ok) {
|
|
var cache = await caches.open(CACHE_NAME);
|
|
cache.put(event.request, networkResponse.clone());
|
|
}
|
|
return networkResponse;
|
|
} catch (err) {
|
|
var cachedResponse = await caches.match(event.request);
|
|
return cachedResponse || new Response('Offline', { status: 503 });
|
|
}
|
|
})()
|
|
);
|
|
});
|
|
|
|
self.addEventListener('activate', function (event) {
|
|
event.waitUntil(
|
|
caches.keys().then(function (cacheNames) {
|
|
return Promise.all(
|
|
cacheNames.filter(function (name) { return name !== CACHE_NAME; }).map(function (name) { return caches.delete(name); })
|
|
);
|
|
}).then(function () { return self.clients.claim(); })
|
|
);
|
|
});
|