initial commit
This commit is contained in:
91
service-worker.js
Normal file
91
service-worker.js
Normal file
@@ -0,0 +1,91 @@
|
||||
const CACHE_NAME = 'dgray-v19';
|
||||
const STATIC_ASSETS = [
|
||||
'/',
|
||||
'/index.html',
|
||||
'/css/fonts.css',
|
||||
'/css/variables.css',
|
||||
'/css/base.css',
|
||||
'/css/components.css',
|
||||
'/js/app.js',
|
||||
'/js/router.js',
|
||||
'/js/i18n.js',
|
||||
'/js/services/api.js',
|
||||
'/locales/de.json',
|
||||
'/locales/en.json',
|
||||
'/locales/fr.json',
|
||||
'/manifest.json',
|
||||
'/assets/fonts/Inter-Regular.woff2',
|
||||
'/assets/fonts/Inter-Medium.woff2',
|
||||
'/assets/fonts/Inter-SemiBold.woff2',
|
||||
'/assets/fonts/Inter-Bold.woff2',
|
||||
'/assets/fonts/SpaceGrotesk-Medium.woff2',
|
||||
'/assets/fonts/SpaceGrotesk-Bold.woff2'
|
||||
];
|
||||
|
||||
self.addEventListener('install', (event) => {
|
||||
event.waitUntil(
|
||||
caches.open(CACHE_NAME)
|
||||
.then((cache) => cache.addAll(STATIC_ASSETS))
|
||||
.then(() => self.skipWaiting())
|
||||
);
|
||||
});
|
||||
|
||||
self.addEventListener('activate', (event) => {
|
||||
event.waitUntil(
|
||||
caches.keys()
|
||||
.then((cacheNames) => {
|
||||
return Promise.all(
|
||||
cacheNames
|
||||
.filter((name) => name !== CACHE_NAME)
|
||||
.map((name) => caches.delete(name))
|
||||
);
|
||||
})
|
||||
.then(() => self.clients.claim())
|
||||
);
|
||||
});
|
||||
|
||||
self.addEventListener('fetch', (event) => {
|
||||
const { request } = event;
|
||||
|
||||
if (request.method !== 'GET') return;
|
||||
|
||||
if (request.url.includes('/api/')) {
|
||||
event.respondWith(networkFirst(request));
|
||||
} else {
|
||||
event.respondWith(cacheFirst(request));
|
||||
}
|
||||
});
|
||||
|
||||
async function cacheFirst(request) {
|
||||
const cached = await caches.match(request);
|
||||
if (cached) return cached;
|
||||
|
||||
try {
|
||||
const response = await fetch(request);
|
||||
if (response.ok) {
|
||||
const cache = await caches.open(CACHE_NAME);
|
||||
cache.put(request, response.clone());
|
||||
}
|
||||
return response;
|
||||
} catch {
|
||||
return new Response('Offline', { status: 503 });
|
||||
}
|
||||
}
|
||||
|
||||
async function networkFirst(request) {
|
||||
try {
|
||||
const response = await fetch(request);
|
||||
if (response.ok) {
|
||||
const cache = await caches.open(CACHE_NAME);
|
||||
cache.put(request, response.clone());
|
||||
}
|
||||
return response;
|
||||
} catch {
|
||||
const cached = await caches.match(request);
|
||||
if (cached) return cached;
|
||||
return new Response(JSON.stringify({ error: 'Offline' }), {
|
||||
status: 503,
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
});
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user