@@ -30,40 +30,64 @@ function rebaseURL(url) {
3030 return ( new URL ( url , registration . scope ) ) . href
3131}
3232
33- function activateHandler ( event ) {
34- event . waitUntil ( ( async function ( ) {
35-
36- //Allow requests by the page to get into browser cache, so that we don't sent 2 requests for the same thing.
37- await new Promise ( ( resolve , reject ) => {
38- setTimeout ( resolve , waitOnFirstLoad )
39- } )
40-
41- const cache = await caches . open ( cacheName )
42- let requests = [ ]
43- for ( let index in preloadList ) {
44- let url = rebaseURL ( preloadList [ index ] )
45- requests . push ( fetch ( url ) )
33+
34+ async function preload ( ) {
35+ //Allow requests by the page to get into browser cache, so that we don't sent 2 requests for the same thing.
36+ await new Promise ( ( resolve , reject ) => {
37+ setTimeout ( resolve , waitOnFirstLoad )
38+ } )
39+
40+ const cache = await caches . open ( cacheName )
41+ let requests = [ ]
42+ for ( let index in preloadList ) {
43+ let url = rebaseURL ( preloadList [ index ] )
44+ requests . push ( fetch ( url ) )
45+ }
46+ for ( let index in requests ) {
47+ let request = requests [ index ]
48+ try {
49+ let response = await request
50+ await cache . put ( response . url , response )
4651 }
47- for ( let index in requests ) {
48- let request = requests [ index ]
49- try {
50- let response = await request
51- await cache . put ( response . url , response )
52- }
53- catch ( e ) {
54- console . error ( e )
55- }
52+ catch ( e ) {
53+ console . error ( e )
5654 }
57- } ) ( ) )
55+ }
5856}
5957
6058
59+ function activateHandler ( event ) {
60+ event . waitUntil ( preload ( ) )
61+ }
6162
6263self . addEventListener ( "activate" , activateHandler )
6364
6465
66+ async function checkForChanges ( ) {
67+ const cache = await caches . open ( cacheName )
68+ let url = "https://api.github.com/repos/ecc521/beginner-javascript-tutorial/commits/master"
69+
70+ let oldResponse = await caches . match ( url )
71+ console . log ( oldResponse )
72+ let oldHash ;
73+ if ( oldResponse ) {
74+ oldHash = ( await oldResponse . json ( ) ) . sha
75+ console . log ( oldHash )
76+ }
77+
78+ let latestCommit = await fetch ( url )
79+ await cache . put ( url , latestCommit . clone ( ) )
80+ let hash = ( await latestCommit . json ( ) ) . sha
6581
82+ console . log ( hash )
83+ console . log ( oldHash )
84+
85+ if ( hash !== oldHash ) {
86+ preload ( )
87+ }
88+ }
6689
90+ checkForChanges ( ) //Not sure exactly when this runs. Should run occasionally though.
6791
6892
6993//Milliseconds to wait for network response before using cache
0 commit comments