feature: add service worker to truly work offline

This commit is contained in:
Jiehong Ma 2021-10-03 17:44:07 +02:00
parent ca6f134036
commit a224fb8f95
2 changed files with 86 additions and 0 deletions

View File

@ -4,6 +4,24 @@
<head> <head>
<meta charset="utf-8"> <meta charset="utf-8">
<title>Jq Play Offline</title> <title>Jq Play Offline</title>
<script>
if('serviceWorker' in navigator) {
navigator.serviceWorker.register('/service_worker.js', { scope: '/' })
.then(function(registration) {
console.log('Service Worker Registered');
})
.catch(e => {
console.log('Unable to register service worker', e);
});
navigator.serviceWorker.ready.then(function(registration) {
console.log('Service Worker Ready');
})
.catch(e => {
console.log('Service worker unable to get ready', e);
});
}
</script>
<link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="style.css">
<script src="https://cdn.biowasm.com/v2/aioli/latest/aioli.js"></script> <script src="https://cdn.biowasm.com/v2/aioli/latest/aioli.js"></script>
<script defer type="module"> <script defer type="module">

68
public/service_worker.js Normal file
View File

@ -0,0 +1,68 @@
const version = "1.0.0";
const cacheName = `jq-offline-${version}`;
self.addEventListener('install', e => {
e.waitUntil(
caches.open(cacheName).then(cache => {
return cache.addAll([
`/index.html`,
`/style.css`
])
.then(() => self.skipWaiting());
})
);
});
self.addEventListener('install', event => {
event.registerForeignFetch({
scopes:['/'],
origins:['*'] // allow all origins
});
});
self.addEventListener('activate', event => {
// Clean up other versions of the caches
event.waitUntil(
caches.keys().then(function(keys) {
return Promise.all(keys
.filter(function(key) {
return key.indexOf(cacheName) !== 0;
})
.map(function(key) {
return caches.delete(key);
})
);
})
);
});
self.addEventListener('fetch', event => {
event.respondWith(
// Get the response from the cache
// or retrieve it, and cache it if not cached yet
caches.match(event.request).then((resp) => {
return resp || fetch(event.request).then((response) => {
let responseClone = response.clone();
caches.open(cacheName).then((cache) => {
console.log('Response was not cached. Caching...');
cache.put(event.request, responseClone);
});
return response;
}).catch(() => {
console.log('Offline, but request not cached. Returning index.html by default.');
return caches.match('./index.html');
});
})
);
});
self.addEventListener('foreignfetch', event => {
// Allow our service worker to correctly see the response from the aioli CDN
// and cache them
event.respondWith(fetch(event.request).then(response => {
return {
response: response,
origin: event.origin,
headers: ['Content-Type']
}
}));
});