summaryrefslogtreecommitdiff
path: root/app/public/sw2.js
blob: 0dabb13fca1399b123b579cf9f9549d55557251f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// https://googlechrome.github.io/samples/service-worker/basic/

const PRECACHE = "notes-precache-v1";
const RUNTIME = "notes-runtime";

const PRECACHE_URLS = [
  "./", // Alias for index.html
  "index.html",
  "style.css",
  "main.js"
];

self.addEventListener("install", e => e.waitUntil(
  caches.open(PRECACHE)
    .then(cache => cache.addAll(PRECACHE_URLS))
    .then(self.skipWaiting())));

self.addEventListener("activate", e => {
  const currentCaches = [PRECACHE, RUNTIME];
  e.waitUntil( // Clean up old caches
    caches.keys().then(cacheNames =>
      cacheNames.filter(cacheName => !currentCaches.includes(cacheName))
    ).then(cachesToDelete => Promise.all(cachesToDelete.map(cacheToDelete =>
      caches.delete(cacheToDelete)))
    ).then(() => self.clients.claim())
  );
});

self.addEventListener("fetch", e => {
  if (e.request.url.startsWith(self.location.origin)) {
    e.respondWith(caches.match(e.request).then(cachedResponse =>
      cachedResponse? cachedResponse
      : caches.open(RUNTIME).then(cache =>
        fetch(e.request).then(res =>
          cache.put(e.request, res.clone()).then(() => res)
        )
      )
    ));
  }
});