Browse Source

New service worker for offline usage

master
Mobius K 2 years ago
parent
commit
8d051a5c6d
  1. 6
      routes/offline.pug
  2. 16
      scripts/index.ts
  3. 37
      scripts/service-worker.ts

6
routes/offline.pug

@ -0,0 +1,6 @@
extends /bluetooth-class/templates/layout
block content
p
a(href="/") ⇐ Return to home page
| Please check your Internet connection, your request could not be completed.

16
scripts/index.ts

@ -6,16 +6,18 @@ import { ErrorMonitor } from "shared/scripts/error-monitor";
// This entire application relies on bitwise operators, so we'll stop tslint from complaining right away
// tslint:disable:no-bitwise
// Start the error watcher for the production environment
if (environment.production) {
// Start the error watcher
new ErrorMonitor("https://ab6fd35ef01e438eb32719f4d92ee084@sentry.io/5178420");
}
// Load our service worker to enable PWA functionality
if ("serviceWorker" in navigator) {
window.addEventListener("load", () => {
navigator.serviceWorker.register("service-worker.js").then();
});
// Load our service worker to enable PWA functionality
if ("serviceWorker" in navigator) {
window.addEventListener("load", () => {
navigator.serviceWorker.register("/service-worker.js").then();
});
}
}
// Container for our bluetooth class code

37
scripts/service-worker.ts

@ -0,0 +1,37 @@
import { ServiceWorkerCache } from "shared/scripts/service-worker-cache";
// Identifier used to ensure browsers are caching the right version of assets
const cacheId = "3";
// Cache manipulator
const cache: ServiceWorkerCache = new ServiceWorkerCache();
// @ts-ignore Install the service worker and cache any files for offline use
self.addEventListener("install", (event: InstallEvent) => {
event.waitUntil(cache.add(cacheId, [
"/404.html",
"/bluetooth-class.css",
"/bluetooth-class.js",
"/favicon.ico",
"/icon.png",
"/index.html",
"/manifest.json",
"/offline.html",
"/robots.txt",
]));
// @ts-ignore Don't require browsers to close and re-open tab
self.skipWaiting();
});
// @ts-ignore Activate the service worker and remove previous caches
self.addEventListener("activate", (event: ExtendableEvent) =>
event.waitUntil(cache.deleteCaches((id: string) => id != cacheId))
);
// @ts-ignore Get requests from cache, network, or a fallback
self.addEventListener("fetch", (event: FetchEvent) =>
event.respondWith(cache.fetchWithCacheOnNetwork(cacheId, event.request, "/offline.html"))
);
Loading…
Cancel
Save