-
-
Save aliams/df8763b7de4d282f019e52b44db1626f to your computer and use it in GitHub Desktop.
Service worker with dynamic caching and cache-first load
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
<script> | |
navigator.serviceWorker.register('sw.js', {scope: '/'}) | |
.then( | |
function (registration) { | |
console.log('Service worker registered!'); | |
}, | |
function (err) { | |
console.error('Installation failed!', err); | |
} | |
); | |
document.addEventListener('DOMContentLoaded', function(event) { | |
showLoading(); | |
var networkDone = false; | |
var networkRequest = fetch('weather.json') | |
.then(function(response) { | |
return response.json(); | |
}) | |
.then(function(json) { | |
networkDone = true; | |
updatePage(json); | |
}); | |
caches.match('weather.json') | |
.then(function(response) { | |
if (!response) throw Error('No data'); | |
return response.json(); | |
}) | |
.then(function(json) { | |
if (!networkDone) updatePage(json); | |
}) | |
.catch(function() {return networkRequest;}) | |
.catch(function() {console.log('We have nothing.');}) | |
.then(hideLoading); | |
}); | |
</script> |
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
self.oninstall = function(event) { | |
event.waitUntil( | |
caches.open('static-v1').then(function(cache) { | |
return cache.addAll([ | |
'/', | |
'/index.html', | |
'/styles.css', | |
'/main.js', | |
'/fallback.html' | |
]); | |
}) | |
); | |
} | |
self.onactivate = function(event) { | |
var keepList = ['assets-v1']; | |
event.waitUntil( | |
caches.keys().then(function(cacheNameList) { | |
return Promise.all(cacheNameList.map(function(cacheName) { | |
if (keepList.indexOf(cacheName) === -1) { | |
return caches.delete(cacheName); | |
} | |
})); | |
}) | |
); | |
} | |
function fetchAndCache(request) { | |
return fetch(request).then(function(response) { | |
caches.open('dynamic').then(function(cache) { | |
cache.put(request, response); | |
}); | |
return response.clone(); | |
}); | |
} | |
self.onfetch = function(event) { | |
if (event.request.url.indexOf('weather.json') !== -1) { | |
event.respondWith(fetchAndCache(event.request)); | |
} else { | |
event.respondWith( | |
caches.match(event.request).then(function(response) { | |
return response || fetchAndCache(event.request); | |
}) | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment