aboutsummaryrefslogtreecommitdiffstats
path: root/sworker.js
blob: 18369fa69d12bc7aabb54affdec303936f959f63 (plain) (blame)
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
var VERSION = 'v69 - 2024-08-22';
var toCache = [
  '/',
  'activePage.js',
  'activePage.js.map',
  'config.js',
  'config.js.map',
  'favicon.ico',
  'hesla.js',
  'hesla.js.map',
  'hesla.webapp',
  'android-chrome-192x192.png',
  'android-chrome-512x512.png',
  'apple-touch-icon.png',
  'favicon-16x16.png',
  'favicon-32x32.png',
  'lamb-of-God.svg',
  'index_de.html',
  'index.html',
  'screen.css',
  'manifest.json'
];

self.addEventListener('install', event => {
    console.log('install version = ' + VERSION);
    event.waitUntil(
      caches.open(VERSION)
      .then(
        c => c.addAll(toCache)
          .then(v => console.log('Yay!' + VERSION), e => console.log('Error'))
      )
    );
});

self.addEventListener('activate', event => {
  console.log('activate version = ' + VERSION);
  console.log('keys:\n' + caches.keys());
  event.waitUntil(caches.keys().then(
        keys => Promise.all(
          keys.filter(key => key != VERSION).
            map(key => caches.delete(key))
        )
    )
  );
});

self.addEventListener('fetch', function(event) {
  event.respondWith(caches.match(event.request).then(function(response) {
    // caches.match() always resolves
    // but in case of success response will have value
    if (response !== undefined) {
      return response;
    } else {
      return fetch(event.request).then(function (response) {
        // response may be used only once
        // we need to save clone to put one copy in cache
        // and serve second one
        let responseClone = response.clone();

        caches.open(VERSION).then(function (cache) {
          cache.put(event.request, responseClone);
        });
        return response;
      }).catch(function () {
        return caches.match('/sw-test/gallery/myLittleVader.jpg');
      });
    }
  }));
});