Try To fetch latest data first then shift to cached one. (#1819)

* fetch latest data first then shift to cached one

* improved offline experience

Co-authored-by: Jeffrey Warren <jeff@unterbahn.com>
This commit is contained in:
Vivek Singh
2021-02-27 22:08:45 +05:30
committed by GitHub
parent 0580218c63
commit 71bf8c872b
3 changed files with 93 additions and 37 deletions

View File

@@ -1,6 +1,14 @@
const staticCacheName = 'image-sequencer-static-v3.6.0';
self.addEventListener('install', event => {
console.log('Attempting to install service worker');
self.addEventListener('install', function(e) {
e.waitUntil(
caches.open(staticCacheName).then(function(cache) {
console.log('Attempting to install service worker');
return cache.addAll([
'/',
'/examples/offline.html'
]);
})
);
});
self.addEventListener('activate', function(e) {
@@ -21,16 +29,28 @@ self.addEventListener('activate', function(e) {
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.open(staticCacheName).then(function(cache) {
return cache.match(event.request).then(function (response) {
return response || fetch(event.request).then(function(response) {
if(event.request.method == 'GET')
cache.put(event.request, response.clone());
return response;
// Try to fetch the latest data first.
fetch(event.request)
.then(function(response) {
return caches.open(staticCacheName)
.then(function(cache) {
if(event.request.method == 'GET'){
cache.put(event.request.url, response.clone());
}
return response;
})
})
.catch(function(err) {
// Now the request has been failed so show cached data.
return caches.match(event.request).then(function(res){
if (res === undefined) {
// Display offline page
return caches.match('offline.html');
}
return res;
});
});
})
);
)
});
// When the update modal sends a 'skipWaiting' message, call the skipWaiting method.