| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | |
| 12 | |
| 13 | |
| 14 | |
| 15 | |
| 16 | |
| 17 | |
| 18 | |
| 19 | |
| 20 | const HOSTNAME_WHITELIST = [ |
| 21 | self.location.hostname, |
| 22 | 'fonts.gstatic.com', |
| 23 | 'fonts.googleapis.com', |
| 24 | 'cdn.jsdelivr.net' |
| 25 | ] |
| 26 | |
| 27 | |
| 28 | const getFixedUrl = (req) => { |
| 29 | var now = Date.now() |
| 30 | var url = new URL(req.url) |
| 31 | |
| 32 | |
| 33 | |
| 34 | |
| 35 | |
| 36 | url.protocol = self.location.protocol |
| 37 | |
| 38 | |
| 39 | |
| 40 | |
| 41 | |
| 42 | |
| 43 | if (url.hostname === self.location.hostname) { |
| 44 | url.search += (url.search ? '&' : '?') + 'cache-bust=' + now |
| 45 | } |
| 46 | return url.href |
| 47 | } |
| 48 | |
| 49 | |
| 50 | |
| 51 | |
| 52 | |
| 53 | |
| 54 | |
| 55 | self.addEventListener('activate', event => { |
| 56 | event.waitUntil(self.clients.claim()) |
| 57 | }) |
| 58 | |
| 59 | |
| 60 | |
| 61 | |
| 62 | |
| 63 | |
| 64 | |
| 65 | self.addEventListener('fetch', event => { |
| 66 | |
| 67 | if (HOSTNAME_WHITELIST.indexOf(new URL(event.request.url).hostname) > -1) { |
| 68 | |
| 69 | |
| 70 | |
| 71 | const cached = caches.match(event.request) |
| 72 | const fixedUrl = getFixedUrl(event.request) |
| 73 | const fetched = fetch(fixedUrl, { cache: 'no-store' }) |
| 74 | const fetchedCopy = fetched.then(resp => resp.clone()) |
| 75 | |
| 76 | |
| 77 | |
| 78 | |
| 79 | |
| 80 | event.respondWith( |
| 81 | Promise.race([fetched.catch(_ => cached), cached]) |
| 82 | .then(resp => resp || fetched) |
| 83 | .catch(_ => { }) |
| 84 | ) |
| 85 | |
| 86 | |
| 87 | event.waitUntil( |
| 88 | Promise.all([fetchedCopy, caches.open("pwa-cache")]) |
| 89 | .then(([response, cache]) => response.ok && cache.put(event.request, response)) |
| 90 | .catch(_ => { }) |
| 91 | ) |
| 92 | } |
| 93 | }) |