-
-
Save kayluhb/2be374c3399692fcaa2ce7b7e1c42be5 to your computer and use it in GitHub Desktop.
Offline SW example
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
/** | |
* 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