Created
December 10, 2018 15:20
-
-
Save Antoinebr/2fd1a6d4733142786a864c969d4bc554 to your computer and use it in GitHub Desktop.
cacheOrNetwiork.js
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
/** | |
* cacheOrNetwork | |
* | |
* Look for and returns an event request in the cache | |
* @param {eventRequest} event | |
* @param {string} cacheName | |
*/ | |
const cacheOrNetwork = async (event, cacheName) => { | |
// Open the cache | |
const cache = await caches.open(cacheName); | |
// check if the requests is in our cache : | |
const responseFromCache = await cache.match(event.request); | |
// if we have the request in the cache | |
if(responseFromCache) { | |
console.log(`[SW] I'm responding to ${event.request.url} from the cache !!`); | |
return responseFromCache; | |
} | |
// If the request is not in the cache : | |
// we can't use the request twice we have to clone it ! | |
const requestToFetch = event.request.clone(); | |
// we fetch the request on the network | |
const responseFromNetwork = await fetch(requestToFetch); | |
// we respond with the fetched request | |
return responseFromNetwork; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment