Improved service worker

This commit is contained in:
Eduard Urbach 2017-07-14 04:58:21 +02:00
parent 815f99ce9c
commit 2e504548c4
3 changed files with 97 additions and 66 deletions

View File

@ -58,7 +58,7 @@ func configure(app *aero.Application) *aero.Application {
app.SetStyle(css.Bundle())
// Sessions
app.Sessions.Duration = 3600 * 24 * 30
app.Sessions.Duration = 3600 * 24 * 30 * 6
app.Sessions.Store = aerospikestore.New(arn.DB, "Session", app.Sessions.Duration)
// Layout

View File

@ -11,6 +11,7 @@ export class AnimeNotifier {
user: HTMLElement
title: string
webpEnabled: boolean
contentLoadedActions: Promise<any>
statusMessage: StatusMessage
visibilityObserver: IntersectionObserver
@ -58,6 +59,7 @@ export class AnimeNotifier {
document.addEventListener("keydown", this.onKeyDown.bind(this), false)
window.addEventListener("popstate", this.onPopState.bind(this))
// Idle
this.requestIdleCallback(this.onIdle.bind(this))
}
@ -108,11 +110,13 @@ export class AnimeNotifier {
// Stop watching all the objects from the previous page.
this.visibilityObserver.disconnect()
this.contentLoadedActions = Promise.all([
Promise.resolve().then(() => this.mountMountables()),
Promise.resolve().then(() => this.lazyLoadImages()),
Promise.resolve().then(() => this.displayLocalDates()),
Promise.resolve().then(() => this.setSelectBoxValue()),
Promise.resolve().then(() => this.assignActions())
])
let headers = document.getElementsByTagName("h1")
@ -138,32 +142,45 @@ export class AnimeNotifier {
registration.update()
})
navigator.serviceWorker.onmessage = evt => {
navigator.serviceWorker.addEventListener("message", evt => {
this.onServiceWorkerMessage(evt)
})
document.addEventListener("DOMContentLoaded", () => {
if(!navigator.serviceWorker.controller) {
return
}
let message = {
type: "loaded",
url: ""
}
if(this.app.lastRequest) {
message.url = this.app.lastRequest.responseURL
} else {
message.url = window.location.href
}
navigator.serviceWorker.controller.postMessage(JSON.stringify(message))
})
}
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) {
case "new content":
if(message.url.includes("/_/")) {
// Content reload
this.contentLoadedActions.then(() => {
this.reloadContent()
})
} else {
// Full page reload
this.contentLoadedActions.then(() => {
this.reloadPage()
}
})
}
break
@ -241,20 +258,7 @@ export class AnimeNotifier {
}
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"))
location.reload()
}
loading(isLoading: boolean) {
@ -414,7 +418,10 @@ export class AnimeNotifier {
let request = fetch("/_" + url, {
credentials: "same-origin"
})
.then(response => response.text())
.then(response => {
this.app.eTag = response.headers.get("ETag")
return response.text()
})
history.pushState(url, null, url)
this.app.currentPath = url

View File

@ -1,8 +1,12 @@
// pack:ignore
var CACHE = "v-1"
const CACHE = "v-1"
const RELOADS = new Map<string, Promise<Response>>()
const ETAGS = new Map<string, string>()
self.addEventListener("install", (evt: any) => {
console.log("Service worker install")
evt.waitUntil(
(self as any).skipWaiting().then(() => {
return installCache()
@ -11,11 +15,51 @@ self.addEventListener("install", (evt: any) => {
})
self.addEventListener("activate", (evt: any) => {
console.log("Service worker activate")
evt.waitUntil(
(self as any).clients.claim()
)
})
// controlling service worker
self.addEventListener("message", (evt: any) => {
let message = JSON.parse(evt.data)
let url = message.url
let refresh = RELOADS.get(url)
let servedETag = ETAGS.get(url)
if(!refresh || !servedETag) {
return
}
evt.waitUntil(
refresh.then((response: Response) => {
// If the fresh copy was used to serve the request instead of the cache,
// we don't need to tell the client to do a refresh.
if(response.bodyUsed) {
return
}
let eTag = response.headers.get("ETag")
if(eTag === servedETag) {
return
}
ETAGS.set(url, eTag)
let message = {
type: "new content",
url
}
return evt.source.postMessage(JSON.stringify(message))
})
)
})
self.addEventListener("fetch", async (evt: any) => {
let request = evt.request
let isAuth = request.url.includes("/auth/") || request.url.includes("/logout")
@ -26,11 +70,11 @@ self.addEventListener("fetch", async (evt: any) => {
}
// Do not use cache in some cases
if(request.method !== "GET" || isAuth) {
if(request.method !== "GET" || isAuth || request.url.includes("chrome-extension")) {
return evt.waitUntil(evt.respondWith(fetch(request)))
}
let servedCachedResponse = false
let servedETag = undefined
// Start fetching the request
let refresh = fetch(request).then(response => {
@ -39,21 +83,14 @@ self.addEventListener("fetch", async (evt: any) => {
// Save the new version of the resource in the cache
caches.open(CACHE).then(cache => {
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
})
// Save in map
RELOADS.set(request.url, refresh)
// Forced reload
if(request.headers.get("X-Reload") === "true") {
return evt.waitUntil(refresh)
@ -61,7 +98,8 @@ self.addEventListener("fetch", async (evt: any) => {
// Try to serve cache first and fall back to network response
let networkOrCache = fromCache(request).then(response => {
servedCachedResponse = true
servedETag = response.headers.get("ETag")
ETAGS.set(request.url, servedETag)
return response
}).catch(error => {
// console.log("Cache MISS:", request.url)
@ -93,17 +131,3 @@ function fromCache(request) {
})
})
}
function reloadContent(response) {
return (self as any).clients.matchAll().then(clients => {
clients.forEach(client => {
var message = {
type: 'content changed',
url: response.url,
eTag: response.headers.get('ETag')
}
client.postMessage(JSON.stringify(message))
})
})
}