1
+ var CACHE = 'cache-and-update-zip' ;
2
+
3
+ // On install, cache some resources.
4
+ self . addEventListener ( 'install' , function ( evt ) {
5
+ console . log ( 'The service worker is being installed.' ) ;
6
+
7
+ // Ask the service worker to keep installing until the returning promise
8
+ // resolves.
9
+ evt . waitUntil ( precache ( ) ) ;
10
+ } ) ;
11
+
12
+ // On fetch, use cache but update the entry with the latest contents
13
+ // from the server.
14
+ self . addEventListener ( 'fetch' , function ( evt ) {
15
+ console . log ( 'The service worker is serving the asset.' ) ;
16
+ // You can use `respondWith()` to answer immediately, without waiting for the
17
+ // network response to reach the service worker...
18
+ evt . respondWith ( fromCache ( evt . request ) ) ;
19
+ // ...and `waitUntil()` to prevent the worker from being killed until the
20
+ // cache is updated.
21
+ evt . waitUntil ( update ( evt . request ) ) ;
22
+ } ) ;
23
+
24
+ // Open a cache and use `addAll()` with an array of assets to add all of them
25
+ // to the cache. Return a promise resolving when all the assets are added.
26
+ function precache ( ) {
27
+ return caches . open ( CACHE ) . then ( function ( cache ) {
28
+ return cache . addAll ( [
29
+ 'index.html' ,
30
+ 'alt.js' ,
31
+ 'jszip.js' ,
32
+ 'filesaver.js'
33
+ ] ) ;
34
+ } ) ;
35
+ }
36
+
37
+ // Open the cache where the assets were stored and search for the requested
38
+ // resource. Notice that in case of no matching, the promise still resolves
39
+ // but it does with `undefined` as value.
40
+ function fromCache ( request ) {
41
+ return caches . open ( CACHE ) . then ( function ( cache ) {
42
+ return cache . match ( request ) . then ( function ( matching ) {
43
+ return matching || Promise . reject ( 'no-match' ) ;
44
+ } ) ;
45
+ } ) ;
46
+ }
47
+
48
+ // Update consists in opening the cache, performing a network request and
49
+ // storing the new response data.
50
+ function update ( request ) {
51
+ return caches . open ( CACHE ) . then ( function ( cache ) {
52
+ return fetch ( request ) . then ( function ( response ) {
53
+ return cache . put ( request , response ) ;
54
+ } ) ;
55
+ } ) ;
56
+ }
0 commit comments