Instantly share code, notes, and snippets.

@janit /sw.js
Last active Aug 19, 2017

Embed
What would you like to do?
Service Worker example for controlling what is cached - See https://malloc.fi/fix-duplicate-redirects-service-worker-caching
self.addEventListener('install', function (event) {
event.waitUntil(preLoad());
});
var preLoad = function () {
// console.log('[PWA Builder] Install Event processing');
return caches.open('pwabuilder-offline').then(function (cache) {
// console.log('[PWA Builder] Cached index and offline page during Install');
return cache.addAll(['/offline.html', '/']);
});
}
self.addEventListener('fetch', function (event) {
// console.log('The service worker is serving the asset.');
event.respondWith(checkResponse(event.request).catch(function () {
return returnFromCache(event.request)
}
));
var storeInCache = true;
var dontCache = [
'sw.js',
'/_redirect'
];
dontCache.forEach(function (element) {
if (event.request.url.includes(element)) {
storeInCache = false;
}
}, this);
if (storeInCache) {
event.waitUntil(addToCache(event.request));
} else {
console.log('do not cache ' + event.request.url);
}
});
var checkResponse = function (request) {
return new Promise(function (fulfill, reject) {
fetch(request).then(function (response) {
if (response.status !== 404) {
fulfill(response)
} else {
reject()
}
}, reject)
});
};
var addToCache = function(request){
return caches.open('pwabuilder-offline').then(function (cache) {
return fetch(request).then(function (response) {
// console.log('[PWA Builder] add page to offline'+response.url)
return cache.put(request, response);
});
});
};
var returnFromCache = function (request) {
return caches.open('pwabuilder-offline').then(function (cache) {
return cache.match(request).then(function (matching) {
if (!matching || matching.status == 404) {
return cache.match('offline.html')
} else {
return matching
}
});
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment