Skip to content

Instantly share code, notes, and snippets.

@ketola
Last active May 27, 2017 12:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ketola/f328a22314b828ff122378b463718bc6 to your computer and use it in GitHub Desktop.
Save ketola/f328a22314b828ff122378b463718bc6 to your computer and use it in GitHub Desktop.
A service worker that returns assets from cache and refreshes them afterwards
// Pre-fetch the assets when the service worker is installed
self.addEventListener('install', function(evt) {
evt.waitUntil(precache());
});
function precache() {
return caches.open(‘your-app-name-cache’).then(function (cache) {
// list all your assets in the array
return cache.addAll([
'/index.html',
'/js/bundle.js',
'/public/css/style.css',
'/manifest.json',
'/sw.js',
'https://api.digitransit.fi/routing/v1/routers/hsl/bike_rental'
]);
});
}
// Everytime the application requests a resource, return it from cache
// and try to refresh it afterwards
self.addEventListener('fetch', function(evt) {
evt.respondWith(fromCache(evt.request));
evt.waitUntil(update(evt.request));
});
function fromCache(request) {
return caches.open(‘your-app-name-cache’).then(function (cache) {
return cache.match(request).then(function (matching) {
return matching || Promise.reject('no-match');
});
});
}
function update(request) {
return caches.open(‘your-app-name-cache’).then(function (cache) {
return fetch(request).then(function (response) {
return cache.put(request, response);
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment