Skip to content

Instantly share code, notes, and snippets.

@iamparthaonline
Last active January 10, 2020 10:02
Show Gist options
  • Select an option

  • Save iamparthaonline/c7084a0a6dc81514ebb4a36577b7b3b9 to your computer and use it in GitHub Desktop.

Select an option

Save iamparthaonline/c7084a0a6dc81514ebb4a36577b7b3b9 to your computer and use it in GitHub Desktop.
const staticAssets = [
'./',
'./styles.css',
'./app.js'
];
self.addEventListener('install', async event => {
const cache = await caches.open('static-meme');
// cache.addAll(staticAssets);
});
self.addEventListener('fetch', event => {
const {request} = event;
const url = new URL(request.url);
if(url.origin === location.origin) {
event.respondWith(cacheData(request));
} else {
event.respondWith(networkFirst(request));
}
});
async function cacheData(request) {
const cachedResponse = await caches.match(request);
return cachedResponse || fetch(request);
}
async function networkFirst(request) {
const cache = await caches.open('dynamic-meme');
try {
const response = await fetch(request);
cache.put(request, response.clone());
return response;
} catch (error){
return await cache.match(request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment