Skip to content

Instantly share code, notes, and snippets.

@anticlergygang
Created August 4, 2019 00:45
Show Gist options
  • Select an option

  • Save anticlergygang/471673b087860b46195d147e95397e56 to your computer and use it in GitHub Desktop.

Select an option

Save anticlergygang/471673b087860b46195d147e95397e56 to your computer and use it in GitHub Desktop.
If the service worker can hit the backend, it requests a fresh index.html, else it goes to the version stored in cache. This is nice because if you update any code that's linked to the html, all you have to do is change the file name to something that's not already in the cache, and it will be stored and used for future requests.
this.addEventListener('fetch', event => {
console.log(`fetch event request url: ${event.request.url}`)
event.respondWith(
caches.match(event.request).then(cacheResponse => {
if (event.request.url.indexOf('.html') !== -1 || event.request.url === `https://www.${domainName}.${tld}/`) {
return fetch(event.request.url).then(response => {
return caches.open(cacheObject.name).then(cache => {
cache.put(event.request, response.clone()).catch(error => {
console.log('Could not add to cache!' + error)
})
return response
}).catch(error => {
console.log('Could not open cache!' + error)
})
}).catch(error => {
if (cacheResponse !== undefined) {
return cacheResponse
} else {
console.log('Resource not found!' + error)
// return with must connect to internet reponse to init client
}
})
} else {
return cacheResponse || fetch(event.request).then(response => {
return caches.open(cacheObject.name).then(cache => {
cache.put(event.request, response.clone()).catch(error => {
console.log('Could not add to cache!' + error)
})
return response
}).catch(error => {
console.log('Could not open cache!' + error)
})
}).catch(error => {
console.log('Resource not found!' + error)
})
}
}).catch(error => {
console.log('Resource not found in the cache!' + error)
})
)
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment