Added network-first responses

This commit is contained in:
Eduard Urbach 2017-12-04 09:45:56 +01:00
parent ae191dd9a4
commit 3f0d28a82b

View File

@ -27,7 +27,6 @@
// to force a real page reload. // to force a real page reload.
// Promises // Promises
const RELOADS = new Map<string, Promise<Response>>()
const CACHEREFRESH = new Map<string, Promise<void>>() const CACHEREFRESH = new Map<string, Promise<void>>()
// E-Tags that we served for a given URL // E-Tags that we served for a given URL
@ -56,13 +55,14 @@ const EXCLUDECACHE = new Set<string>([
// Authorization paths /auth/ and /logout are not listed here because they are handled in a special way. // Authorization paths /auth/ and /logout are not listed here because they are handled in a special way.
]) ])
// MyServiceWorker is the process that controls all the tabs in a browser. // MyServiceWorker is the process that controls all the tabs in a browser.
class MyServiceWorker { class MyServiceWorker {
cache: MyCache cache: MyCache
reloads: Map<string, Promise<Response>>
constructor() { constructor() {
this.cache = new MyCache("v-5") this.cache = new MyCache("v-5")
this.reloads = new Map<string, Promise<Response>>()
self.addEventListener("install", (evt: InstallEvent) => evt.waitUntil(this.onInstall(evt))) self.addEventListener("install", (evt: InstallEvent) => evt.waitUntil(this.onInstall(evt)))
self.addEventListener("activate", (evt: any) => evt.waitUntil(this.onActivate(evt))) self.addEventListener("activate", (evt: any) => evt.waitUntil(this.onActivate(evt)))
@ -110,9 +110,11 @@ class MyServiceWorker {
// If it's not a GET request, fetch it normally // If it's not a GET request, fetch it normally
if(request.method !== "GET") { if(request.method !== "GET") {
return evt.respondWith(fetch(request)) return evt.respondWith(this.fromNetwork(request))
} }
console.log("Fetch:", request.url)
// Clear cache on authentication and fetch it normally // Clear cache on authentication and fetch it normally
if(request.url.includes("/auth/") || request.url.includes("/logout")) { if(request.url.includes("/auth/") || request.url.includes("/logout")) {
return evt.respondWith(caches.delete(this.cache.version).then(() => fetch(request))) return evt.respondWith(caches.delete(this.cache.version).then(() => fetch(request)))
@ -121,7 +123,7 @@ class MyServiceWorker {
// Exclude certain URLs from being cached // Exclude certain URLs from being cached
for(let pattern of EXCLUDECACHE.keys()) { for(let pattern of EXCLUDECACHE.keys()) {
if(request.url.includes(pattern)) { if(request.url.includes(pattern)) {
return evt.respondWith(fetch(request)) return evt.respondWith(this.fromNetwork(request))
} }
} }
@ -143,31 +145,34 @@ class MyServiceWorker {
CACHEREFRESH.set(request.url, cacheRefresh) CACHEREFRESH.set(request.url, cacheRefresh)
// Force reload page if styles changed // // Force reload page if styles changed
if(request.url.endsWith("/styles")) { // if(request.url.endsWith("/styles")) {
let servedETag = ETAGS.get(request.url) // let servedETag = ETAGS.get(request.url)
let newETag = response.headers.get("ETag") // let newETag = response.headers.get("ETag")
console.log("/styles fetched", servedETag, newETag) // console.log("/styles fetched", servedETag, newETag)
if(servedETag && servedETag !== newETag) { // if(servedETag && servedETag !== newETag) {
cacheRefresh.then(async () => { // cacheRefresh.then(async () => {
console.log("tell client to reload style") // console.log("tell client to reload style")
let client = await MyClient.get(evt.clientId) // let client = await MyClient.get(evt.clientId)
client.reloadStyles() // client.reloadStyles()
}) // })
} // }
} // }
return response return response
}).catch(error => {
console.log("Fetch error:", error)
throw error
}) })
// Save in map // Save in map
RELOADS.set(request.url, refresh) this.reloads.set(request.url, refresh)
// Forced reload // Forced reload
let servedETag = undefined let servedETag = undefined
let onResponse = response => { let onResponse = (response: Response) => {
servedETag = response.headers.get("ETag") servedETag = response.headers.get("ETag")
ETAGS.set(request.url, servedETag) ETAGS.set(request.url, servedETag)
return response return response
@ -177,13 +182,33 @@ class MyServiceWorker {
return evt.respondWith(refresh.then(onResponse)) return evt.respondWith(refresh.then(onResponse))
} }
// Try to serve cache first and fall back to network response // Scripts and styles are server pushed on the initial response
let networkOrCache = this.fromCache(request).then(onResponse).catch(error => { // so we can use a network-first response for those.
// console.log("Cache MISS:", request.url) if(request.url.endsWith("/styles") || request.url.endsWith("/scripts")) {
// Serve network first.
// Fall back to cache.
let networkResponse = refresh.then(response => {
console.log("Network HIT:", request.url)
return response
}).catch(error => {
console.log("Network MISS:", request.url)
return this.fromCache(request).then(onResponse)
})
return evt.respondWith(networkResponse)
} else {
// Serve cache first.
// Fall back to network.
let cacheResponse = this.fromCache(request).then(response => {
console.log("Cache HIT:", request.url)
return onResponse(response)
}).catch(error => {
console.log("Cache MISS:", request.url)
return refresh return refresh
}) })
return evt.respondWith(networkOrCache) return evt.respondWith(cacheResponse)
}
} }
async onMessage(evt: ServiceWorkerMessageEvent) { async onMessage(evt: ServiceWorkerMessageEvent) {
@ -290,6 +315,10 @@ class MyServiceWorker {
}) })
}) })
} }
fromNetwork(request) {
return fetch(request)
}
} }
// MyCache is the cache used by the service worker. // MyCache is the cache used by the service worker.
@ -331,7 +360,7 @@ class MyClient {
// onDOMContentLoaded is called when the client sent this service worker // onDOMContentLoaded is called when the client sent this service worker
// a message that the page has been loaded. // a message that the page has been loaded.
onDOMContentLoaded(url: string) { onDOMContentLoaded(url: string) {
let refresh = RELOADS.get(url) let refresh = serviceWorker.reloads.get(url)
let servedETag = ETAGS.get(url) let servedETag = ETAGS.get(url)
// If the user requests a sub-page we should prefetch the full page, too. // If the user requests a sub-page we should prefetch the full page, too.
@ -393,7 +422,7 @@ class MyClient {
}) })
// Save in map // Save in map
RELOADS.set(fullPage.url, fullPageRefresh) serviceWorker.reloads.set(fullPage.url, fullPageRefresh)
} }
async reloadContent(url: string) { async reloadContent(url: string) {
@ -410,7 +439,7 @@ class MyClient {
} }
async reloadPage(url: string) { async reloadPage(url: string) {
let networkFetch = RELOADS.get(url.replace("/_/", "/")) let networkFetch = serviceWorker.reloads.get(url.replace("/_/", "/"))
if(networkFetch) { if(networkFetch) {
await networkFetch await networkFetch