Last active
June 1, 2019 21:33
-
-
Save Verdi/e287619f09ad569cff851a2b1902f9e0 to your computer and use it in GitHub Desktop.
Serviceworker for twine game
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const version = 'V0.03'; | |
const staticCacheName = version + 'staticfiles'; | |
addEventListener('install', installEvent => { | |
skipWaiting(); | |
installEvent.waitUntil( | |
caches.open(staticCacheName) | |
.then(staticCache =>{ | |
// These files don't block installation | |
staticCache.addAll([ | |
]); // end addAll | |
// These files must be cached for installation | |
return staticCache.addAll([ | |
'/index.html', | |
'/images/image.jpg' | |
]); // end retrun addAll | |
}) // end open then | |
); // end waitUntil | |
}); // end addEventListener | |
addEventListener('activate', activateEvent => { | |
activateEvent.waitUntil( | |
caches.keys() | |
.then( cacheNames => { | |
return Promise.all( | |
cacheNames.map( cacheName => { | |
if (cacheName != staticCacheName) { | |
return caches.delete(cacheName); | |
} // end if | |
}) // end map | |
); // end return Promise.all | |
}) // end keys then | |
.then( () => { | |
return clients.claim(); | |
}) // end then | |
); // end waitUntil | |
}); // end addEventListener | |
addEventListener('fetch', fetchEvent => { | |
// console.log('The service worker is listening.'); | |
const request = fetchEvent.request; | |
console.log(request); | |
fetchEvent.respondWith( | |
// First, look in the cache | |
caches.match(request) | |
.then(responseFromCache =>{ | |
if(responseFromCache){ | |
return responseFromCache; | |
} // end if | |
// Otherwise fetch from the network | |
return fetch(request) | |
.catch(error =>{ | |
return caches.match('/index.html'); | |
}); // end fetch catch and return | |
}) // end match then | |
); // end respondWith | |
}); // end addEventListener |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment