Skip to content

Commit dd4e621

Browse files
committed
updated sw
1 parent 95b18ca commit dd4e621

5 files changed

Lines changed: 400 additions & 66 deletions

File tree

‎cache.manifest‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
CACHE MANIFEST
2-
# Build: 20170602094159
2+
# Build: 20170602104328
33

44
CACHE:
55
resources/fonts/Dressedless_Three.svg

‎index.html‎

Lines changed: 2 additions & 2 deletions
Large diffs are not rendered by default.

‎static/app/html/scripts.html‎

Lines changed: 126 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,14 +11,132 @@
1111
</script>
1212
<script>
1313
if ('serviceWorker' in navigator) {
14-
window.addEventListener('load', function() {
15-
navigator.serviceWorker.register('sw.js').then(function(registration) {
16-
// Registration was successful
17-
console.log('ServiceWorker registration successful with scope: ', registration.scope);
18-
}, function(err) {
19-
// registration failed :(
20-
console.log('ServiceWorker registration failed: ', err);
14+
if (!Cache.prototype.add) {
15+
Cache.prototype.add = function add(request) {
16+
return this.addAll([request]);
17+
};
18+
}
19+
20+
if (!Cache.prototype.addAll) {
21+
Cache.prototype.addAll = function addAll(requests) {
22+
var cache = this;
23+
24+
// Since DOMExceptions are not constructable:
25+
function NetworkError(message) {
26+
this.name = 'NetworkError';
27+
this.code = 19;
28+
this.message = message;
29+
}
30+
NetworkError.prototype = Object.create(Error.prototype);
31+
32+
return Promise.resolve().then(function() {
33+
if (arguments.length < 1) throw new TypeError();
34+
35+
// Simulate sequence<(Request or USVString)> binding:
36+
var sequence = [];
37+
38+
requests = requests.map(function(request) {
39+
if (request instanceof Request) {
40+
return request;
41+
}
42+
else {
43+
return String(request); // may throw TypeError
44+
}
45+
});
46+
47+
return Promise.all(
48+
requests.map(function(request) {
49+
if (typeof request === 'string') {
50+
request = new Request(request);
51+
}
52+
53+
var scheme = new URL(request.url).protocol;
54+
55+
if (scheme !== 'http:' && scheme !== 'https:') {
56+
throw new NetworkError("Invalid scheme");
57+
}
58+
59+
return fetch(request.clone());
60+
})
61+
);
62+
}).then(function(responses) {
63+
// TODO: check that requests don't overwrite one another
64+
// (don't think this is possible to polyfill due to opaque responses)
65+
return Promise.all(
66+
responses.map(function(response, i) {
67+
return cache.put(requests[i], response);
68+
})
69+
);
70+
}).then(function() {
71+
return undefined;
72+
});
73+
};
74+
}
75+
76+
if (!CacheStorage.prototype.match) {
77+
// This is probably vulnerable to race conditions (removing caches etc)
78+
CacheStorage.prototype.match = function match(request, opts) {
79+
var caches = this;
80+
81+
return this.keys().then(function(cacheNames) {
82+
var match;
83+
84+
return cacheNames.reduce(function(chain, cacheName) {
85+
return chain.then(function() {
86+
return match || caches.open(cacheName).then(function(cache) {
87+
return cache.match(request, opts);
88+
}).then(function(response) {
89+
match = response;
90+
return match;
91+
});
92+
});
93+
}, Promise.resolve());
94+
});
95+
};
96+
}
97+
98+
if ('serviceWorker' in navigator) {
99+
// Delay registration until after the page has loaded, to ensure that our
100+
// precaching requests don't degrade the first visit experience.
101+
// See https://developers.google.com/web/fundamentals/instant-and-offline/service-worker/registration
102+
window.addEventListener('load', function() {
103+
// Your service-worker.js *must* be located at the top-level directory relative to your site.
104+
// It won't be able to control pages unless it's located at the same level or higher than them.
105+
// *Don't* register service worker file in, e.g., a scripts/ sub-directory!
106+
// See https://github.com/slightlyoff/ServiceWorker/issues/468
107+
navigator.serviceWorker.register('sw.js').then(function(reg) {
108+
// updatefound is fired if service-worker.js changes.
109+
reg.onupdatefound = function() {
110+
// The updatefound event implies that reg.installing is set; see
111+
// https://slightlyoff.github.io/ServiceWorker/spec/service_worker/index.html#service-worker-container-updatefound-event
112+
var installingWorker = reg.installing;
113+
114+
installingWorker.onstatechange = function() {
115+
switch (installingWorker.state) {
116+
case 'installed':
117+
if (navigator.serviceWorker.controller) {
118+
// At this point, the old content will have been purged and the fresh content will
119+
// have been added to the cache.
120+
// It's the perfect time to display a "New content is available; please refresh."
121+
// message in the page's interface.
122+
console.log('New or updated content is available.');
123+
} else {
124+
// At this point, everything has been precached.
125+
// It's the perfect time to display a "Content is cached for offline use." message.
126+
console.log('Content is now available offline!');
127+
}
128+
break;
129+
130+
case 'redundant':
131+
console.error('The installing service worker became redundant.');
132+
break;
133+
}
134+
};
135+
};
136+
}).catch(function(e) {
137+
console.error('Error during service worker registration:', e);
138+
});
21139
});
22-
});
140+
}
23141
}
24142
</script>

‎static/app/sw.js‎

Lines changed: 135 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,144 @@
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+
432
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+
743
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+
);
12109
})
13110
);
14111
});
15112

16-
// The fetch event happens for the page request with the
17-
// ServiceWorker's scope, and any request made within that
18-
// page
19113
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);
23115
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+
);
36144
});

0 commit comments

Comments
 (0)