Added service worker

This commit is contained in:
Eduard Urbach 2017-07-14 00:11:25 +02:00
parent 3740ec61d6
commit 1a5cd8494e
4 changed files with 121 additions and 22 deletions

View File

@ -5,7 +5,7 @@
.login-button .login-button
padding 0.5rem padding 0.5rem
color white
.login-button-image :hover
max-width 236px color white
max-height 44px

View File

@ -99,6 +99,9 @@ export class AnimeNotifier {
// Let"s start // Let"s start
this.app.run() this.app.run()
// Service worker
this.registerServiceWorker()
} }
onContentLoaded() { onContentLoaded() {
@ -123,18 +126,50 @@ export class AnimeNotifier {
} }
onIdle() { onIdle() {
this.registerServiceWorker()
this.pushAnalytics() this.pushAnalytics()
} }
registerServiceWorker() { registerServiceWorker() {
if(!("serviceWorker" in navigator)) {
return
}
navigator.serviceWorker.register("service-worker", { navigator.serviceWorker.register("service-worker", {
scope: "./" scope: "./"
}).then(registration => {
registration.update()
}) })
// navigator.serviceWorker.ready.then(() => { navigator.serviceWorker.onmessage = evt => {
// console.log("Service worker registered.") this.onServiceWorkerMessage(evt)
// }) }
}
onServiceWorkerMessage(evt: ServiceWorkerMessageEvent) {
let message = JSON.parse(evt.data)
console.log(message.url, this.app.eTag, message.eTag)
switch(message.type) {
case "content changed":
// If we don't have an etag it means it was a full page refresh.
// In this case we don't need to reload anything.
if(!this.app.eTag) {
this.app.eTag = message.eTag
return
}
if(this.app.eTag !== message.eTag) {
if(message.url.includes("/_/")) {
// Content reload
this.reloadContent()
} else {
// Full page reload
this.reloadPage()
}
}
break
}
} }
pushAnalytics() { pushAnalytics() {
@ -185,14 +220,39 @@ export class AnimeNotifier {
} }
reloadContent() { reloadContent() {
let headers = new Headers()
headers.append("X-Reload", "true")
return fetch("/_" + this.app.currentPath, { return fetch("/_" + this.app.currentPath, {
credentials: "same-origin" credentials: "same-origin",
headers
})
.then(response => {
this.app.eTag = response.headers.get("ETag")
return response
}) })
.then(response => response.text()) .then(response => response.text())
.then(html => Diff.innerHTML(this.app.content, html)) .then(html => Diff.innerHTML(this.app.content, html))
.then(() => this.app.emit("DOMContentLoaded")) .then(() => this.app.emit("DOMContentLoaded"))
} }
reloadPage() {
let headers = new Headers()
headers.append("X-Reload", "true")
return fetch(this.app.currentPath, {
credentials: "same-origin",
headers
})
.then(response => {
this.app.eTag = response.headers.get("ETag")
return response
})
.then(response => response.text())
.then(html => Diff.innerHTML(document.body, html))
.then(() => this.app.emit("DOMContentLoaded"))
}
loading(isLoading: boolean) { loading(isLoading: boolean) {
if(isLoading) { if(isLoading) {
document.body.style.cursor = "progress" document.body.style.cursor = "progress"

View File

@ -13,6 +13,7 @@ export class Application {
loading: HTMLElement loading: HTMLElement
currentPath: string currentPath: string
originalPath: string originalPath: string
eTag: string
lastRequest: XMLHttpRequest lastRequest: XMLHttpRequest
constructor() { constructor() {
@ -45,6 +46,8 @@ export class Application {
request.onerror = () => reject(new Error("You are either offline or the requested page doesn't exist.")) request.onerror = () => reject(new Error("You are either offline or the requested page doesn't exist."))
request.ontimeout = () => reject(new Error("The page took too much time to respond.")) request.ontimeout = () => reject(new Error("The page took too much time to respond."))
request.onload = () => { request.onload = () => {
this.eTag = request.getResponseHeader("ETag")
if(request.status < 200 || request.status >= 400) if(request.status < 200 || request.status >= 400)
reject(request.responseText) reject(request.responseText)
else else

View File

@ -1,26 +1,36 @@
// pack:ignore // pack:ignore
var CACHE = "v-alpha" var CACHE = "v-1"
self.addEventListener("install", (evt: any) => { self.addEventListener("install", (evt: any) => {
console.log("The service worker is being installed.") evt.waitUntil(
(self as any).skipWaiting().then(() => {
evt.waitUntil(installCache()) return installCache()
})
)
}) })
self.addEventListener("activate", (evt: any) => { self.addEventListener("activate", (evt: any) => {
evt.waitUntil((self as any).clients.claim()) evt.waitUntil(
(self as any).clients.claim()
)
}) })
self.addEventListener("fetch", async (evt: any) => { self.addEventListener("fetch", async (evt: any) => {
let request = evt.request let request = evt.request
let isAuth = request.url.includes("/auth/") || request.url.includes("/logout")
console.log("Serving:", request.url, request, request.method) // Delete existing cache on authentication
if(isAuth) {
caches.delete(CACHE)
}
// Do not use cache in some cases // Do not use cache in some cases
if(request.method !== "GET" || request.url.includes("/auth/") || request.url.includes("chrome-extension")) { if(request.method !== "GET" || isAuth || request.url.includes("chrome-extension")) {
return evt.waitUntil(evt.respondWith(fetch(request))) return evt.waitUntil(evt.respondWith(fetch(request)))
} }
let servedCachedResponse = false
// Start fetching the request // Start fetching the request
let refresh = fetch(request).then(response => { let refresh = fetch(request).then(response => {
@ -28,15 +38,33 @@ self.addEventListener("fetch", async (evt: any) => {
// Save the new version of the resource in the cache // Save the new version of the resource in the cache
caches.open(CACHE).then(cache => { caches.open(CACHE).then(cache => {
cache.put(request, clone) return cache.put(request, clone)
}).then(() => {
if(!servedCachedResponse) {
return
}
let contentType = clone.headers.get("Content-Type")
if(contentType && contentType.startsWith("text/html") && clone.headers.get("ETag") && request.headers.get("X-Reload") !== "true") {
reloadContent(clone)
}
}) })
return response return response
}) })
// Forced reload
if(request.headers.get("X-Reload") === "true") {
return evt.waitUntil(refresh)
}
// Try to serve cache first and fall back to network response // Try to serve cache first and fall back to network response
let networkOrCache = fromCache(request).catch(error => { let networkOrCache = fromCache(request).then(response => {
console.log("Cache MISS:", request.url) servedCachedResponse = true
return response
}).catch(error => {
// console.log("Cache MISS:", request.url)
return refresh return refresh
}) })
@ -57,7 +85,7 @@ function fromCache(request) {
return caches.open(CACHE).then(cache => { return caches.open(CACHE).then(cache => {
return cache.match(request).then(matching => { return cache.match(request).then(matching => {
if(matching) { if(matching) {
console.log("Cache HIT:", request.url) // console.log("Cache HIT:", request.url)
return Promise.resolve(matching) return Promise.resolve(matching)
} }
@ -66,8 +94,16 @@ function fromCache(request) {
}) })
} }
function updateCache(request, response) { function reloadContent(response) {
return caches.open(CACHE).then(cache => { return (self as any).clients.matchAll().then(clients => {
cache.put(request, response) clients.forEach(client => {
var message = {
type: 'content changed',
url: response.url,
eTag: response.headers.get('ETag')
}
client.postMessage(JSON.stringify(message))
})
}) })
} }