-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsw.js
executable file
·59 lines (41 loc) · 1.33 KB
/
sw.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
const CACHE_NAME = 'STORIES_CACHE-v2';
self.addEventListener('install',function(){
// Guardar archivos iniciales
caches.open(CACHE_NAME).then(function(cache){
cache.addAll(['/index.html','/dist/javascript/bundle.js','/public/images/1.jpg']);
})
});
self.addEventListener('activate',function(ev){
ev.waitUntil(
caches.keys().then(function(cacheNames){
let promises = cacheNames.map(cacheName => {
if(CACHE_NAME !== cacheName) return caches.delete(cacheName);
});
return Promise.all(promises);
})
);
});
self.addEventListener('fetch',function(ev){
ev.respondWith(
caches.match(ev.request)
.then(function(response){
return searchInCacheOrMakeRequest(ev.request);
}).catch(function(err){
if(ev.request.mode == "navigate")
return caches.match(ev.request);
})
);
});
function searchInCacheOrMakeRequest(request){
const cachePromise = caches.open(CACHE_NAME);
const matchPromise = cachePromise.then(function(cache){
return cache.match(request);
});
return Promise.all([cachePromise,matchPromise]).then(function([cache,cacheResponse]){
const fetchPromise = fetch(request).then(function(fetchResponse){
cache.put(request,fetchResponse.clone());
return fetchResponse;
});
return cacheResponse || fetchPromise;
});
}