Skip to content

Instantly share code, notes, and snippets.

@kayluhb
Forked from deanhume/offline-swer.js
Last active August 24, 2016 16:00
Show Gist options
  • Save kayluhb/2be374c3399692fcaa2ce7b7e1c42be5 to your computer and use it in GitHub Desktop.
Save kayluhb/2be374c3399692fcaa2ce7b7e1c42be5 to your computer and use it in GitHub Desktop.
Offline SW example
/**
* Helper method to determine the filename from the URL
* @param {url} the path to match
* @return {String} the path for caching
**/
function getFilenameFromUrl(url){
var path = url.substring(path.lastIndexOf("/")+ 1);
return (path.match(/[^.]+(\.[^?#]+)?/) || [])[0];
}
/**
* Callback function to check the URL in the cache
* @param {request} the request object
* @return {Boolean} if the request is allowed
**/
function isRequestAllowed(request) {
return request.mode === 'navigate' || (
request.method === 'GET' && request.headers.get('accept').includes('text/html')
)
}
/**
* Callback function to check the URL in the cache
* @param {event} the event from the fetch listener
* @return {void}
**/
function onFetch(event) {
if (!isRequestAllowed(request)) {
return;
}
event.respondWith(
fetch(event.request.url).catch(error => {
var cachedFile = getFilenameFromUrl(event.request.url);
// Return the offline page
return caches.match(cachedFile);
})
);
}
this.addEventListener('fetch', onFetch);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment