Add PWA + ServiceWorker with offline support

This commit is contained in:
Daniel Supernault 2021-06-17 22:42:08 -06:00
parent 22c321a998
commit 78ee44662c
No known key found for this signature in database
GPG Key ID: 0DEF1C662C9033F7
3 changed files with 113 additions and 1 deletions

61
public/offline.html Normal file

File diff suppressed because one or more lines are too long

45
public/sw.js vendored Normal file
View File

@ -0,0 +1,45 @@
const OFFLINE_VERSION = 1;
const CACHE_NAME = "offline";
const OFFLINE_URL = "/offline.html";
self.addEventListener("install", (event) => {
event.waitUntil(
(async () => {
const cache = await caches.open(CACHE_NAME);
await cache.add(new Request(OFFLINE_URL, { cache: "reload" }));
})()
);
self.skipWaiting();
});
self.addEventListener("activate", (event) => {
event.waitUntil(
(async () => {
if ("navigationPreload" in self.registration) {
await self.registration.navigationPreload.enable();
}
})()
);
self.clients.claim();
});
self.addEventListener("fetch", (event) => {
if (event.request.mode === "navigate") {
event.respondWith(
(async () => {
try {
const preloadResponse = await event.preloadResponse;
if (preloadResponse) {
return preloadResponse;
}
const networkResponse = await fetch(event.request);
return networkResponse;
} catch (error) {
const cache = await caches.open(CACHE_NAME);
const cachedResponse = await cache.match(OFFLINE_URL);
return cachedResponse;
}
})()
);
}
});

View File

@ -34,6 +34,12 @@ window.App.boot = function() {
new Vue({ el: '#content'}); new Vue({ el: '#content'});
} }
window.addEventListener("load", () => {
if ("serviceWorker" in navigator) {
navigator.serviceWorker.register("/sw.js");
}
});
window.App.util = { window.App.util = {
compose: { compose: {
post: (function() { post: (function() {
@ -230,4 +236,4 @@ window.App.util = {
.attr('width', 34).attr('height', 34); .attr('width', 34).attr('height', 34);
}) })
}; };