Skip to content

Instantly share code, notes, and snippets.

@Antoinebr
Created December 10, 2018 15:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Antoinebr/2fd1a6d4733142786a864c969d4bc554 to your computer and use it in GitHub Desktop.
Save Antoinebr/2fd1a6d4733142786a864c969d4bc554 to your computer and use it in GitHub Desktop.
cacheOrNetwiork.js
/**
* 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