|
| 1 | +/* |
| 2 | + Copyright 2014 Google Inc. All Rights Reserved. |
| 3 | + Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | + you may not use this file except in compliance with the License. |
| 5 | + You may obtain a copy of the License at |
| 6 | + http://www.apache.org/licenses/LICENSE-2.0 |
| 7 | + Unless required by applicable law or agreed to in writing, software |
| 8 | + distributed under the License is distributed on an "AS IS" BASIS, |
| 9 | + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 10 | + See the License for the specific language governing permissions and |
| 11 | + limitations under the License. |
| 12 | + */ |
| 13 | + |
| 14 | +// While overkill for this specific sample in which there is only one cache, |
| 15 | +// this is one best practice that can be followed in general to keep track of |
| 16 | +// multiple caches used by a given service worker, and keep them all versioned. |
| 17 | +// It maps a shorthand identifier for a cache to a specific, versioned cache name. |
| 18 | + |
| 19 | +// Note that since global state is discarded in between service worker restarts, these |
| 20 | +// variables will be reinitialized each time the service worker handles an event, and you |
| 21 | +// should not attempt to change their values inside an event handler. (Treat them as constants.) |
| 22 | + |
| 23 | +// If at any point you want to force pages that use this service worker to start using a fresh |
| 24 | +// cache, then increment the CACHE_VERSION value. It will kick off the service worker update |
| 25 | +// flow and the old cache(s) will be purged as part of the activate event handler when the |
| 26 | +// updated service worker is activated. |
| 27 | +var CACHE_VERSION = 20181227122100; |
| 28 | +var CURRENT_CACHES = { |
| 29 | + prefetch: 'prefetch-cache-v' + CACHE_VERSION |
| 30 | +}; |
| 31 | + |
| 32 | +self.addEventListener('install', function(event) { |
| 33 | + var now = Date.now(); |
| 34 | + |
| 35 | + var urlsToPrefetch = ["./", |
| 36 | +"css/app.79a153d0.css", |
| 37 | +"css/app.css", |
| 38 | +"css/lib.365f8ae0.css", |
| 39 | +"css/lib.css", |
| 40 | +"css/styles.css", |
| 41 | +"css/styles.d06dda8f.css", |
| 42 | +"fonts/Dressedless_Three.svg", |
| 43 | +"fonts/Dressedless_Three.ttf", |
| 44 | +"fonts/FontAwesome.otf", |
| 45 | +"fonts/LatoLatin-Bold.woff2", |
| 46 | +"fonts/LatoLatin-BoldItalic.woff2", |
| 47 | +"fonts/LatoLatin-Italic.woff2", |
| 48 | +"fonts/LatoLatin-Regular.woff2", |
| 49 | +"fonts/fontawesome-webfont.eot", |
| 50 | +"fonts/fontawesome-webfont.svg", |
| 51 | +"fonts/fontawesome-webfont.ttf", |
| 52 | +"fonts/fontawesome-webfont.woff", |
| 53 | +"fonts/fontawesome-webfont.woff2", |
| 54 | +"images/404_dribbble.ae94d03c.gif", |
| 55 | +"images/404_dribbble.gif", |
| 56 | +"images/codelf_logo.f4ae25bd.png", |
| 57 | +"images/codelf_logo.png", |
| 58 | +"images/paypal.69412e83.png", |
| 59 | +"images/paypal.png", |
| 60 | +"images/twohardtings.0db8462a.jpg", |
| 61 | +"images/twohardtings.jpg", |
| 62 | +"images/wechatpay.48ba089d.jpg", |
| 63 | +"images/wechatpay.jpg", |
| 64 | +"images/zhifubao.70c19370.png", |
| 65 | +"images/zhifubao.png", |
| 66 | +"js/app.f0f29d58.js", |
| 67 | +"js/app.js", |
| 68 | +"js/app.js.map", |
| 69 | +"js/lib.2ef380a5.js", |
| 70 | +"js/lib.js", |
| 71 | +"css/themes/default/assets/fonts/brand-icons.eot", |
| 72 | +"css/themes/default/assets/fonts/brand-icons.svg", |
| 73 | +"css/themes/default/assets/fonts/brand-icons.ttf", |
| 74 | +"css/themes/default/assets/fonts/brand-icons.woff", |
| 75 | +"css/themes/default/assets/fonts/brand-icons.woff2", |
| 76 | +"css/themes/default/assets/fonts/icons.eot", |
| 77 | +"css/themes/default/assets/fonts/icons.otf", |
| 78 | +"css/themes/default/assets/fonts/icons.svg", |
| 79 | +"css/themes/default/assets/fonts/icons.ttf", |
| 80 | +"css/themes/default/assets/fonts/icons.woff", |
| 81 | +"css/themes/default/assets/fonts/icons.woff2", |
| 82 | +"css/themes/default/assets/fonts/outline-icons.eot", |
| 83 | +"css/themes/default/assets/fonts/outline-icons.svg", |
| 84 | +"css/themes/default/assets/fonts/outline-icons.ttf", |
| 85 | +"css/themes/default/assets/fonts/outline-icons.woff", |
| 86 | +"css/themes/default/assets/fonts/outline-icons.woff2", |
| 87 | +"css/themes/default/assets/images/flags.png"]; |
| 88 | + |
| 89 | + // All of these logging statements should be visible via the "Inspect" interface |
| 90 | + // for the relevant SW accessed via chrome://serviceworker-internals |
| 91 | + console.log('Handling install event. Resources to prefetch:', urlsToPrefetch); |
| 92 | + |
| 93 | + event.waitUntil( |
| 94 | + caches.open(CURRENT_CACHES.prefetch).then(function(cache) { |
| 95 | + var cachePromises = urlsToPrefetch.map(function(urlToPrefetch) { |
| 96 | + // This constructs a new URL object using the service worker's script location as the base |
| 97 | + // for relative URLs. |
| 98 | + var url = new URL(urlToPrefetch, location.href); |
| 99 | + // Append a cache-bust=TIMESTAMP URL parameter to each URL's query string. |
| 100 | + // This is particularly important when precaching resources that are later used in the |
| 101 | + // fetch handler as responses directly, without consulting the network (i.e. cache-first). |
| 102 | + // If we were to get back a response from the HTTP browser cache for this precaching request |
| 103 | + // then that stale response would be used indefinitely, or at least until the next time |
| 104 | + // the service worker script changes triggering the install flow. |
| 105 | + url.search += (url.search ? '&' : '?') + 'cache-bust=' + now; |
| 106 | + |
| 107 | + // It's very important to use {mode: 'no-cors'} if there is any chance that |
| 108 | + // the resources being fetched are served off of a server that doesn't support |
| 109 | + // CORS (http://en.wikipedia.org/wiki/Cross-origin_resource_sharing). |
| 110 | + // In this example, www.chromium.org doesn't support CORS, and the fetch() |
| 111 | + // would fail if the default mode of 'cors' was used for the fetch() request. |
| 112 | + // The drawback of hardcoding {mode: 'no-cors'} is that the response from all |
| 113 | + // cross-origin hosts will always be opaque |
| 114 | + // (https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#cross-origin-resources) |
| 115 | + // and it is not possible to determine whether an opaque response represents a success or failure |
| 116 | + // (https://github.com/whatwg/fetch/issues/14). |
| 117 | + var request = new Request(url, {mode: 'no-cors'}); |
| 118 | + return fetch(request).then(function(response) { |
| 119 | + if (response.status >= 400) { |
| 120 | + throw new Error('request for ' + urlToPrefetch + |
| 121 | + ' failed with status ' + response.statusText); |
| 122 | + } |
| 123 | + |
| 124 | + // Use the original URL without the cache-busting parameter as the key for cache.put(). |
| 125 | + return cache.put(urlToPrefetch, response); |
| 126 | + }).catch(function(error) { |
| 127 | + console.error('Not caching ' + urlToPrefetch + ' due to ' + error); |
| 128 | + }); |
| 129 | + }); |
| 130 | + |
| 131 | + return Promise.all(cachePromises).then(function() { |
| 132 | + console.log('Pre-fetching complete.'); |
| 133 | + }); |
| 134 | + }).catch(function(error) { |
| 135 | + console.error('Pre-fetching failed:', error); |
| 136 | + }) |
| 137 | + ); |
| 138 | +}); |
| 139 | + |
| 140 | +self.addEventListener('activate', function(event) { |
| 141 | + // Delete all caches that aren't named in CURRENT_CACHES. |
| 142 | + // While there is only one cache in this example, the same logic will handle the case where |
| 143 | + // there are multiple versioned caches. |
| 144 | + var expectedCacheNames = Object.keys(CURRENT_CACHES).map(function(key) { |
| 145 | + return CURRENT_CACHES[key]; |
| 146 | + }); |
| 147 | + |
| 148 | + event.waitUntil( |
| 149 | + caches.keys().then(function(cacheNames) { |
| 150 | + return Promise.all( |
| 151 | + cacheNames.map(function(cacheName) { |
| 152 | + if (expectedCacheNames.indexOf(cacheName) === -1) { |
| 153 | + // If this cache name isn't present in the array of "expected" cache names, then delete it. |
| 154 | + console.log('Deleting out of date cache:', cacheName); |
| 155 | + return caches.delete(cacheName); |
| 156 | + } |
| 157 | + }) |
| 158 | + ); |
| 159 | + }) |
| 160 | + ); |
| 161 | +}); |
| 162 | + |
| 163 | +self.addEventListener('fetch', function(event) { |
| 164 | + console.log('Handling fetch event for', event.request.url); |
| 165 | + var requestURL = new URL(event.request.url); |
| 166 | + requestURL.origin == location.origin && event.respondWith( |
| 167 | + // caches.match() will look for a cache entry in all of the caches available to the service worker. |
| 168 | + // It's an alternative to first opening a specific named cache and then matching on that. |
| 169 | + caches.match(event.request).then(function(response) { |
| 170 | + if (response) { |
| 171 | + console.log('Found response in cache:', response); |
| 172 | + |
| 173 | + return response; |
| 174 | + } |
| 175 | + |
| 176 | + console.log('No response found in cache. About to fetch from network...'); |
| 177 | + |
| 178 | + // event.request will always have the proper mode set ('cors, 'no-cors', etc.) so we don't |
| 179 | + // have to hardcode 'no-cors' like we do when fetch()ing in the install handler. |
| 180 | + return fetch(event.request).then(function(response) { |
| 181 | + console.log('Response from network is:', response); |
| 182 | + |
| 183 | + return response; |
| 184 | + }).catch(function(error) { |
| 185 | + // This catch() will handle exceptions thrown from the fetch() operation. |
| 186 | + // Note that a HTTP error response (e.g. 404) will NOT trigger an exception. |
| 187 | + // It will return a normal response object that has the appropriate error code set. |
| 188 | + console.error('Fetching failed:', error); |
| 189 | + |
| 190 | + throw error; |
| 191 | + }); |
| 192 | + }) |
| 193 | + ); |
| 194 | +}); |
0 commit comments