Created
January 27, 2016 15:00
-
-
Save felquis/986b69c2aa64956186da to your computer and use it in GitHub Desktop.
Service Worker: Ignore request endpoints with RegEx
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
// This polyfill provides Cache.add(), Cache.addAll(), and CacheStorage.match(), | |
// which are not implemented in Chrome 40. | |
importScripts('js/cache-polyfill.js') // find it on the internet | |
var version = 'v01234567' | |
var ignoreRequests = new RegExp('(' + [ | |
'\.com/', // customize to your use case, home page | |
'/page1', | |
'/perfil', | |
'/perfil\/(.*)', // ignore also IDs | |
'/feedback'].join('(\/?)|\\') + ')$') | |
/* | |
examples | |
ignoreRequests.test('https://site.com/') // true | |
ignoreRequests.test('https://site.com/any/') // false, will be cached | |
ignoreRequests.test('https://site.com/perfil/123') // true | |
*/ | |
function onFetch(event) { | |
if (ignoreRequests.test(event.request.url)) { | |
console.log('ignored: ', event.request.url) | |
// request will be networked | |
return | |
} | |
event.respondWith(fetchAndCache(event)) | |
} | |
function fetchAndCache(event) { | |
return caches | |
.match(event.request) | |
.then(function(cached) { | |
var networked = fetch(event.request) | |
.then(fetchedFromNetwork(event)) | |
return cached || networked | |
}) | |
} | |
function fetchedFromNetwork(event) { | |
return function transform(response) { | |
var cacheCopy = response.clone() | |
caches | |
.open(version) | |
.then(function add(cache) { | |
cache.put(event.request, cacheCopy) | |
}) | |
.then(function() { | |
// console.log('WORKER: fetch response stored in cache.', event.request.url) | |
}) | |
return response | |
} | |
} | |
self.addEventListener('fetch', onFetch) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment