arnaucube
arnaucube/study-labPublic Self-hosted repository
study-lab/service-worker.js
service-worker.jsRaw
 1const CACHE_NAME = 'study-lab-shell-v4';
 2const APP_SHELL = [
 3  './',
 4  './index.html',
 5  './styles.css',
 6  './app.js',
 7  './manifest.webmanifest',
 8  './icons/icon-192.png',
 9  './icons/icon-512.png',
10  './icons/icon-maskable-512.png',
11  './icons/apple-touch-icon.png'
12];
13
14self.addEventListener('install', event => {
15  event.waitUntil(caches.open(CACHE_NAME).then(cache => cache.addAll(APP_SHELL)));
16  self.skipWaiting();
17});
18
19self.addEventListener('activate', event => {
20  event.waitUntil(
21    caches.keys()
22      .then(keys => Promise.all(keys.filter(key => key !== CACHE_NAME).map(key => caches.delete(key))))
23      .then(() => self.clients.claim())
24  );
25});
26
27self.addEventListener('fetch', event => {
28  if (event.request.method !== 'GET') return;
29
30  const url = new URL(event.request.url);
31  if (url.origin !== self.location.origin) return;
32
33  event.respondWith(
34    fetch(event.request)
35      .then(response => {
36        if (response.ok) {
37          const copy = response.clone();
38          caches.open(CACHE_NAME).then(cache => cache.put(event.request, copy));
39        }
40        return response;
41      })
42      .catch(async () => {
43        const cached = await caches.match(event.request);
44        if (cached) return cached;
45        if (event.request.mode === 'navigate') return caches.match('./index.html');
46        return Response.error();
47      })
48  );
49});