|
| 1 | +--- |
| 2 | +--- |
| 3 | +const version = '{{ site.time | date: '%Y%m%d%H%M%S' }}'; |
| 4 | +const cacheName = `static::${version}`; |
| 5 | + |
| 6 | +const buildContentBlob = () => { |
| 7 | + return [ |
| 8 | + {%- for post in site.posts limit: 10 -%} |
| 9 | + "{{ post.url }}", |
| 10 | + {%- endfor -%} |
| 11 | + {%- for page in site.pages -%} |
| 12 | + {%- unless page.url contains 'sw.js' -%} |
| 13 | + "{{ page.url }}", |
| 14 | + {%- endunless -%} |
| 15 | + {%- endfor -%} |
| 16 | + "/assets/logo.svg","/assets/styles.css" |
| 17 | + ] |
| 18 | +} |
| 19 | + |
| 20 | +const updateStaticCache = () => { |
| 21 | + return caches.open(cacheName).then(cache => { |
| 22 | + return cache.addAll(buildContentBlob()); |
| 23 | + }); |
| 24 | +}; |
| 25 | + |
| 26 | +const clearOldCache = () => { |
| 27 | + return caches.keys().then(keys => { |
| 28 | + // Remove caches whose name is no longer valid. |
| 29 | + return Promise.all( |
| 30 | + keys |
| 31 | + .filter(key => { |
| 32 | + return key !== cacheName; |
| 33 | + }) |
| 34 | + .map(key => { |
| 35 | + console.log(`Service Worker: removing cache ${key}`); |
| 36 | + return caches.delete(key); |
| 37 | + }) |
| 38 | + ); |
| 39 | + }); |
| 40 | +}; |
| 41 | + |
| 42 | +self.addEventListener("install", event => { |
| 43 | + event.waitUntil( |
| 44 | + updateStaticCache().then(() => { |
| 45 | + console.log(`Service Worker: cache updated to version: ${cacheName}`); |
| 46 | + }) |
| 47 | + ); |
| 48 | +}); |
| 49 | + |
| 50 | +self.addEventListener("activate", event => { |
| 51 | + event.waitUntil(clearOldCache()); |
| 52 | +}); |
| 53 | + |
| 54 | +self.addEventListener("fetch", event => { |
| 55 | + let request = event.request; |
| 56 | + let url = new URL(request.url); |
| 57 | + |
| 58 | + // Only deal with requests from the same domain. |
| 59 | + if (url.origin !== location.origin) { |
| 60 | + return; |
| 61 | + } |
| 62 | + |
| 63 | + // Always fetch non-GET requests from the network. |
| 64 | + if (request.method !== "GET") { |
| 65 | + event.respondWith(fetch(request)); |
| 66 | + return; |
| 67 | + } |
| 68 | + |
| 69 | + // For HTML requests, try the network first else fall back to the offline page. |
| 70 | + if (request.headers.get("Accept").indexOf("text/html") !== -1) { |
| 71 | + event.respondWith(fetch(request).catch(() => caches.match(event.request))); |
| 72 | + return; |
| 73 | + } |
| 74 | + |
| 75 | + // For non-HTML requests, look in the cache first else fall back to the network. |
| 76 | + event.respondWith( |
| 77 | + caches.match(request).then(response => { |
| 78 | + if (response) { |
| 79 | + console.log("Serving cached: ", event.request.url); |
| 80 | + return response; |
| 81 | + } |
| 82 | + console.log("Fetching: ", event.request.url); |
| 83 | + return fetch(request); |
| 84 | + }) |
| 85 | + ); |
| 86 | +}); |
0 commit comments