Last active
May 27, 2017 12:46
-
-
Save ketola/f328a22314b828ff122378b463718bc6 to your computer and use it in GitHub Desktop.
A service worker that returns assets from cache and refreshes them afterwards
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
// 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