generated from Chrstjan/Js-Boilerplate-2.0
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sw.js
53 lines (48 loc) · 1.44 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
//This caches what's in the cacheAssets array
//name of the cache version
const cacheName = "v1";
//Array with what we want to cache
const cacheAssets = [
"index.html",
"./assets/css/base.css",
"./assets/css/header.css",
"./assets/css/main.css",
"./assets/css/footer.css",
"./assets/js/bundles.js"
];
// calling the install event
self.addEventListener("install", (e) => {
console.log("Service Worker: Installed");
e.waitUntil(
caches
.open(cacheName)
.then(cache => {
console.log("Service Worker: Caching Files");
cache.addAll(cacheAssets);
})
.then(() => self.skipWaiting())
);
})
// calling the activate event
self.addEventListener("activate", (e) => {
console.log("Service Worker: Activated");
//Remove unwanted caches
e.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cache => {
if(cache !== cacheName) {
console.log("Service Worker: Clearing Old Cache");
return caches.delete(cache);
}
})
)
})
);
});
//Call fetch event
self.addEventListener("fetch", (e) => {
console.log("Service Worker: Fetching");
//Checks if the live site is available else load from the cache
e.respondWith(fetch(e.request).catch(() => caches.match(e.request)));
});