|
1 | | -// Here comes the install event! |
2 | | -// This only happens once, when the browser sees this |
3 | | -// version of the ServiceWorker for the first time. |
| 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 = _BUILD_VERSION_; |
| 28 | +var CURRENT_CACHES = { |
| 29 | + prefetch: 'prefetch-cache-v' + CACHE_VERSION |
| 30 | +}; |
| 31 | + |
4 | 32 | self.addEventListener('install', function(event) { |
5 | | - // We pass a promise to event.waitUntil to signal how |
6 | | - // long install takes, and if it failed |
| 33 | + var now = Date.now(); |
| 34 | + |
| 35 | + var urlsToPrefetch = [ |
| 36 | + cache.addAll([_FILES_]); |
| 37 | + ]; |
| 38 | + |
| 39 | + // All of these logging statements should be visible via the "Inspect" interface |
| 40 | + // for the relevant SW accessed via chrome://serviceworker-internals |
| 41 | + console.log('Handling install event. Resources to prefetch:', urlsToPrefetch); |
| 42 | + |
7 | 43 | event.waitUntil( |
8 | | - // We open a cache… |
9 | | - caches.open('_BUILD_VERSION_').then(function(cache) { |
10 | | - // And add resources to it |
11 | | - return cache.addAll([_FILES_]); |
| 44 | + caches.open(CURRENT_CACHES.prefetch).then(function(cache) { |
| 45 | + var cachePromises = urlsToPrefetch.map(function(urlToPrefetch) { |
| 46 | + // This constructs a new URL object using the service worker's script location as the base |
| 47 | + // for relative URLs. |
| 48 | + var url = new URL(urlToPrefetch, location.href); |
| 49 | + // Append a cache-bust=TIMESTAMP URL parameter to each URL's query string. |
| 50 | + // This is particularly important when precaching resources that are later used in the |
| 51 | + // fetch handler as responses directly, without consulting the network (i.e. cache-first). |
| 52 | + // If we were to get back a response from the HTTP browser cache for this precaching request |
| 53 | + // then that stale response would be used indefinitely, or at least until the next time |
| 54 | + // the service worker script changes triggering the install flow. |
| 55 | + url.search += (url.search ? '&' : '?') + 'cache-bust=' + now; |
| 56 | + |
| 57 | + // It's very important to use {mode: 'no-cors'} if there is any chance that |
| 58 | + // the resources being fetched are served off of a server that doesn't support |
| 59 | + // CORS (http://en.wikipedia.org/wiki/Cross-origin_resource_sharing). |
| 60 | + // In this example, www.chromium.org doesn't support CORS, and the fetch() |
| 61 | + // would fail if the default mode of 'cors' was used for the fetch() request. |
| 62 | + // The drawback of hardcoding {mode: 'no-cors'} is that the response from all |
| 63 | + // cross-origin hosts will always be opaque |
| 64 | + // (https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#cross-origin-resources) |
| 65 | + // and it is not possible to determine whether an opaque response represents a success or failure |
| 66 | + // (https://github.com/whatwg/fetch/issues/14). |
| 67 | + var request = new Request(url, {mode: 'no-cors'}); |
| 68 | + return fetch(request).then(function(response) { |
| 69 | + if (response.status >= 400) { |
| 70 | + throw new Error('request for ' + urlToPrefetch + |
| 71 | + ' failed with status ' + response.statusText); |
| 72 | + } |
| 73 | + |
| 74 | + // Use the original URL without the cache-busting parameter as the key for cache.put(). |
| 75 | + return cache.put(urlToPrefetch, response); |
| 76 | + }).catch(function(error) { |
| 77 | + console.error('Not caching ' + urlToPrefetch + ' due to ' + error); |
| 78 | + }); |
| 79 | + }); |
| 80 | + |
| 81 | + return Promise.all(cachePromises).then(function() { |
| 82 | + console.log('Pre-fetching complete.'); |
| 83 | + }); |
| 84 | + }).catch(function(error) { |
| 85 | + console.error('Pre-fetching failed:', error); |
| 86 | + }) |
| 87 | + ); |
| 88 | +}); |
| 89 | + |
| 90 | +self.addEventListener('activate', function(event) { |
| 91 | + // Delete all caches that aren't named in CURRENT_CACHES. |
| 92 | + // While there is only one cache in this example, the same logic will handle the case where |
| 93 | + // there are multiple versioned caches. |
| 94 | + var expectedCacheNames = Object.keys(CURRENT_CACHES).map(function(key) { |
| 95 | + return CURRENT_CACHES[key]; |
| 96 | + }); |
| 97 | + |
| 98 | + event.waitUntil( |
| 99 | + caches.keys().then(function(cacheNames) { |
| 100 | + return Promise.all( |
| 101 | + cacheNames.map(function(cacheName) { |
| 102 | + if (expectedCacheNames.indexOf(cacheName) === -1) { |
| 103 | + // If this cache name isn't present in the array of "expected" cache names, then delete it. |
| 104 | + console.log('Deleting out of date cache:', cacheName); |
| 105 | + return caches.delete(cacheName); |
| 106 | + } |
| 107 | + }) |
| 108 | + ); |
12 | 109 | }) |
13 | 110 | ); |
14 | 111 | }); |
15 | 112 |
|
16 | | -// The fetch event happens for the page request with the |
17 | | -// ServiceWorker's scope, and any request made within that |
18 | | -// page |
19 | 113 | self.addEventListener('fetch', function(event) { |
20 | | - // Calling event.respondWith means we're in charge |
21 | | - // of providing the response. We pass in a promise |
22 | | - // that resolves with a response object |
| 114 | + console.log('Handling fetch event for', event.request.url); |
23 | 115 | var requestURL = new URL(event.request.url); |
24 | | - if (requestURL.origin == location.origin) { |
25 | | - event.respondWith( |
26 | | - // First we look for something in the caches that |
27 | | - // matches the request |
28 | | - caches.match(event.request).then(function(response) { |
29 | | - // If we get something, we return it, otherwise |
30 | | - // it's null, and we'll pass the request to |
31 | | - // fetch, which will use the network. |
32 | | - return response || fetch(event.request); |
33 | | - }) |
34 | | - ); |
35 | | - } |
| 116 | + requestURL.origin == location.origin && event.respondWith( |
| 117 | + // caches.match() will look for a cache entry in all of the caches available to the service worker. |
| 118 | + // It's an alternative to first opening a specific named cache and then matching on that. |
| 119 | + caches.match(event.request).then(function(response) { |
| 120 | + if (response) { |
| 121 | + console.log('Found response in cache:', response); |
| 122 | + |
| 123 | + return response; |
| 124 | + } |
| 125 | + |
| 126 | + console.log('No response found in cache. About to fetch from network...'); |
| 127 | + |
| 128 | + // event.request will always have the proper mode set ('cors, 'no-cors', etc.) so we don't |
| 129 | + // have to hardcode 'no-cors' like we do when fetch()ing in the install handler. |
| 130 | + return fetch(event.request).then(function(response) { |
| 131 | + console.log('Response from network is:', response); |
| 132 | + |
| 133 | + return response; |
| 134 | + }).catch(function(error) { |
| 135 | + // This catch() will handle exceptions thrown from the fetch() operation. |
| 136 | + // Note that a HTTP error response (e.g. 404) will NOT trigger an exception. |
| 137 | + // It will return a normal response object that has the appropriate error code set. |
| 138 | + console.error('Fetching failed:', error); |
| 139 | + |
| 140 | + throw error; |
| 141 | + }); |
| 142 | + }) |
| 143 | + ); |
36 | 144 | }); |
0 commit comments