-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsw.js
More file actions
91 lines (86 loc) · 2.31 KB
/
sw.js
File metadata and controls
91 lines (86 loc) · 2.31 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
const offline = 'offlineV1'
const otherScriptsCache = 'scripts'
const offlineAssets = [
'index.html',
'about.html',
'/css/style.css',
'/js/main.js',
'/js/placeholder.js'
]
const isCacheable = ( url ) => {
return [
/list.js/
].map(item => new RegExp(item).test(url)).some(v => v === true)
}
self.addEventListener('install', (event) => {
console.log('Service worker: Installed')
event.waitUntil(
caches
.open(offline)
.then(cache => {
console.log('Service worker: Caching offline file')
cache.addAll(offlineAssets)
})
.then(() => self.skipWaiting())
)
})
self.addEventListener('activate', (event) => {
console.log('Service worker: Activated')
event.waitUntil(
clients.claim().then(() => {
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cache => {
if (cache !== offline) {
console.log('Service worker: Clearing old cache')
return caches.delete(cache)
}
})
)
})
})
)
})
self.addEventListener('fetch', (event) => {
console.log('Service worker: Fetching', event.request.url)
if(isCacheable(event.request.url)) {
console.log('Service worker: Arquivo cacheável ', event.request.url)
event.respondWith(
fetch(event.request)
.then(res => {
const resClone = res.clone()
event.waitUntil(
caches.open(otherScriptsCache)
.then(cache => {
cache.put(event.request, resClone)
})
)
return res;
})
.catch(() => {
return caches.match(event.request)
.then(res => {
if (res) return res
else {
console.log('Não foi possível encontrar o cache para ', event.request.url)
return caches.match('/js/placeholder.js')
}
})
})
)
}
else {
event.respondWith(
fetch(event.request).catch(function() {
return caches.match(event.request)
.then(res => {
if(res) return res
else {
console.log('Não foi possível encontrar o cache para ', event.request.url)
return caches.match('/js/placeholder.js')
}
})
})
)
}
})