-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathservice-worker.js
More file actions
96 lines (85 loc) · 1.8 KB
/
service-worker.js
File metadata and controls
96 lines (85 loc) · 1.8 KB
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
// Service Worker: Cache management for HTTP/HTTPS deployment
var CACHE_VERSION='manga-editor-v1';
var STATIC_EXTENSIONS=[
'.css','.js','.png','.jpg','.jpeg','.gif','.svg','.ico',
'.woff','.woff2','.ttf','.eot','.otf',
'.html','.json'
];
function isStaticAsset(url){
var pathname=url.pathname.toLowerCase();
return STATIC_EXTENSIONS.some(function(ext){
return pathname.endsWith(ext);
});
}
function isApiCall(url){
return url.pathname.includes('/api/');
}
self.addEventListener('install',function(event){
self.skipWaiting();
});
self.addEventListener('activate',function(event){
event.waitUntil(
caches.keys().then(function(keys){
return Promise.all(
keys.filter(function(key){
return key!==CACHE_VERSION;
}).map(function(key){
return caches.delete(key);
})
);
}).then(function(){
return self.clients.claim();
})
);
});
self.addEventListener('fetch',function(event){
var url=new URL(event.request.url);
if(url.protocol==='file:'){
return;
}
if(!url.pathname.startsWith('/')){
return;
}
if(event.request.method!=='GET'){
return;
}
if(isApiCall(url)){
event.respondWith(
fetch(event.request).then(function(response){
var clone=response.clone();
caches.open(CACHE_VERSION).then(function(cache){
cache.put(event.request,clone);
});
return response;
}).catch(function(){
return caches.match(event.request);
})
);
return;
}
if(isStaticAsset(url)){
event.respondWith(
caches.match(event.request).then(function(cached){
if(cached){
return cached;
}
return fetch(event.request).then(function(response){
if(!response||response.status!==200||response.type!=='basic'){
return response;
}
var clone=response.clone();
caches.open(CACHE_VERSION).then(function(cache){
cache.put(event.request,clone);
});
return response;
});
})
);
return;
}
event.respondWith(
fetch(event.request).catch(function(){
return caches.match(event.request);
})
);
});