Add a simple service worker to make an installable app

This commit is contained in:
Eike Kettner
2020-09-18 22:59:58 +02:00
parent b5f3c64058
commit d3bf03482e
4 changed files with 68 additions and 3 deletions

View File

@ -46,6 +46,13 @@
};
</script>
<script type="application/javascript" src="{{appExtraJs}}"></script>
<script>
if('serviceWorker' in navigator) {
navigator.serviceWorker
.register('/sw.js')
.then(function() { console.log("Service Worker Registered"); });
}
</script>
</body>
</html>

View File

@ -0,0 +1,37 @@
// use a cacheName for cache versioning
var cacheName = 'v1:static';
// during the install phase you usually want to cache static assets
self.addEventListener('install', function(e) {
// once the SW is installed, go ahead and fetch the resources to make this work offline
e.waitUntil(
caches.open(cacheName).then(function(cache) {
return cache.addAll([
{{# cssUrls }}
'{{.}}',
{{/ cssUrls }}
{{# jsUrls }}
'{{.}}',
{{/ jsUrls}}
'{{appExtraJs}}'
]).then(function() {
self.skipWaiting();
});
})
);
});
// when the browser fetches a url
self.addEventListener('fetch', function(event) {
// either respond with the cached object or go ahead and fetch the actual url
event.respondWith(
caches.match(event.request).then(function(response) {
if (response) {
// retrieve from cache
return response;
}
// fetch as normal
return fetch(event.request);
})
);
});