1 | var staticCacheName = "pwa-v" + new Date().getTime();
|
---|
2 | var filesToCache = [
|
---|
3 | '/offline',
|
---|
4 | '/css/app.css',
|
---|
5 | '/js/app.js',
|
---|
6 | '/images/icons/icon-72x72.png',
|
---|
7 | '/images/icons/icon-96x96.png',
|
---|
8 | '/images/icons/icon-128x128.png',
|
---|
9 | '/images/icons/icon-144x144.png',
|
---|
10 | '/images/icons/icon-152x152.png',
|
---|
11 | '/images/icons/icon-192x192.png',
|
---|
12 | '/images/icons/icon-384x384.png',
|
---|
13 | '/images/icons/icon-512x512.png',
|
---|
14 | ];
|
---|
15 |
|
---|
16 | // Cache on install
|
---|
17 | self.addEventListener("install", event => {
|
---|
18 | this.skipWaiting();
|
---|
19 | event.waitUntil(
|
---|
20 | caches.open(staticCacheName)
|
---|
21 | .then(cache => {
|
---|
22 | return cache.addAll(filesToCache);
|
---|
23 | })
|
---|
24 | )
|
---|
25 | });
|
---|
26 |
|
---|
27 | // Clear cache on activate
|
---|
28 | self.addEventListener('activate', event => {
|
---|
29 | event.waitUntil(
|
---|
30 | caches.keys().then(cacheNames => {
|
---|
31 | return Promise.all(
|
---|
32 | cacheNames
|
---|
33 | .filter(cacheName => (cacheName.startsWith("pwa-")))
|
---|
34 | .filter(cacheName => (cacheName !== staticCacheName))
|
---|
35 | .map(cacheName => caches.delete(cacheName))
|
---|
36 | );
|
---|
37 | })
|
---|
38 | );
|
---|
39 | });
|
---|
40 |
|
---|
41 | // Serve from Cache
|
---|
42 | self.addEventListener("fetch", event => {
|
---|
43 | event.respondWith(
|
---|
44 | caches.match(event.request)
|
---|
45 | .then(response => {
|
---|
46 | return response || fetch(event.request);
|
---|
47 | })
|
---|
48 | .catch(() => {
|
---|
49 | return caches.match('offline');
|
---|
50 | })
|
---|
51 | )
|
---|
52 | }); |
---|