-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
service-worker.js
99 lines (87 loc) · 2.8 KB
/
service-worker.js
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
// jshint esversion:6
var me = self,
CACHE_NAME = 'interst8xy',
urlsToCache = [
'/',
'/?utm_source=web_app_manifest',
'/index.html',
'/assets/Overpass_Regular-webfont.eot',
'/assets/Overpass_Regular-webfont.svg',
'/assets/Overpass_Regular-webfont.ttf',
'/assets/Overpass_Regular-webfont.woff',
'/assets/images/logo.svg',
'/css/overpass.css',
'/css/style.css',
'/js/game.js',
'/js/service-worker-handler.js',
'/data/levels.json',
'/manifest.json'
];
me.addEventListener('install', function(event) {
event.waitUntil(precache());
});
me.addEventListener('fetch', function(event) {
event.respondWith(fromNetwork(event.request, 400).catch(function () {
return fromCache(event.request);
}));
});
me.addEventListener('activate', function(event) {
event.waitUntil(
caches.keys().then(function(cacheNames) {
return Promise.all(
cacheNames.map(function(cacheName) {
if (cacheName !== CACHE_NAME) {
return caches.delete(cacheName);
}
})
);
})
);
});
me.addEventListener('message', function(event) {
if (event.data.action === 'skipWaiting') {
me.skipWaiting();
}
});
function precache() {
return caches.open(CACHE_NAME)
.then(function(cache) {
return fetch('/data/levels.json').then(function(response) {
return response.json();
})
.then(function(levelManifest) {
var levelDataFiles = levelManifest.map(function (levelData) {
return levelData.data;
});
urlsToCache = urlsToCache.concat(levelDataFiles);
var levelIconFiles = levelManifest.map(function (levelData) {
return levelData.icon;
});
urlsToCache = urlsToCache.concat(levelIconFiles);
return cache.addAll(urlsToCache);
});
});
}
function fromCache(request) {
return caches.open(CACHE_NAME).then(function (cache) {
return cache.match(request).then(function (matching) {
return matching || Promise.reject('no-match');
});
});
}
function fromNetwork(request, timeout) {
return new Promise(function (fulfill, reject) {
var timeoutId = setTimeout(reject, timeout);
fetch(request).then(function (response) {
clearTimeout(timeoutId);
fulfill(response);
}, reject);
});
}
function update(request) {
return caches.open(CACHE_NAME).then(function (cache) {
return fetch(request).then(function (response) {
return cache.put(request, response);
});
});
}