Skip to content

Commit

Permalink
feat: add service worker
Browse files Browse the repository at this point in the history
  • Loading branch information
zeromake committed Jul 29, 2024
1 parent 44b2fb9 commit 5fc3dfd
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 10 deletions.
17 changes: 9 additions & 8 deletions themes/even/assets/js/service-worker-template.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ self.addEventListener('activate', event => {
return Promise.all(
cacheNames.map(cacheName => caches.delete(cacheName)),
);
}).then(() => {
self.registration.unregister();
}),
);
});
Expand Down Expand Up @@ -39,9 +41,9 @@ self.addEventListener('fetch', event => {
caches
.match(event.request)
.then(response => {
var skip = false;
var skip = event.request.url.startsWith('https://api.github.com');
{{- if .Site.BuildDrafts -}}
skip = filesToCache.filter(name => event.request.url.endsWith(name)).length === 0;
skip ||= filesToCache.filter(name => event.request.url.endsWith(name)).length === 0;
{{- end -}}
if (!skip && response) return response;
return fetch(event.request);
Expand Down Expand Up @@ -76,15 +78,14 @@ self.addEventListener('fetch', event => {

// Delete outdated caches
self.addEventListener('activate', event => {
const cacheWhitelist = [cacheName];
event.waitUntil(
caches.keys().then(cacheNames => {
return Promise.all(
cacheNames.map(cacheName => {
if (!cacheWhitelist.includes(cacheName)) {
return caches.delete(cacheName);
}
}),
cacheNames.filter(
cacheName => cacheName !== cacheName
).map(
cacheName => caches.delete(cacheName)
),
);
}),
);
Expand Down
9 changes: 7 additions & 2 deletions themes/even/layouts/partials/scripts.html
Original file line number Diff line number Diff line change
Expand Up @@ -179,8 +179,13 @@
{{- $serviceWorker := resources.Get "js/service-worker-template.js" | resources.ExecuteAsTemplate "service-worker.js" . -}}
<script>
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('{{ $serviceWorker.Permalink }}').then(function() {
console.log('[ServiceWorker] Registered');
navigator.serviceWorker.getRegistrations().then(regs=>{
for (const reg of regs) {
reg.unregister();
}
navigator.serviceWorker.register('{{ $serviceWorker.Permalink }}').then(function() {
console.log('[ServiceWorker] Registered');
});
});
}
</script>
Expand Down

0 comments on commit 5fc3dfd

Please sign in to comment.