diff --git a/app/views/service_worker/index.js.erb b/app/views/service_worker/index.js.erb index 2097d145f..5bf5cf509 100644 --- a/app/views/service_worker/index.js.erb +++ b/app/views/service_worker/index.js.erb @@ -37,40 +37,45 @@ function createPageStream(request) { const stream = new ReadableStream({ start(controller) { - if (!caches.match('/shell_top') || !caches.match('/shell_bottom')) { //return if shell isn't cached. - return - } + Promise.all([caches.match('/shell_top'), caches.match('/shell_bottom')]) + .then((cachedShellMatches) => { + const cachedShellTop = cachedShellMatches[0]; + const cachedShellBottom = cachedShellMatches[1]; + if (!cachedShellTop || !cachedShellBottom) { // return if shell isn't cached. + return + } + // the body url is the request url plus 'include' + const url = new URL(request.url); + url.searchParams.set('i', 'i'); // Adds ?i=i or &i=i, which is our indicator for "internal" partial page + const startFetch = Promise.resolve(cachedShellTop); + const endFetch = Promise.resolve(cachedShellBottom); + const middleFetch = fetch(url).then(response => { + if (!response.ok && response.status === 404) { + return caches.match('/404.html'); + } + if (!response.ok && response.status != 404) { + return caches.match('/500.html'); + } + return response; + }).catch(err => caches.match('/offline.html')); - // the body url is the request url plus 'include' - const url = new URL(request.url); - url.searchParams.set('i', 'i'); // Adds ?i=i or &i=i, which is our indicator for "internal" partial page - const startFetch = caches.match('/shell_top'); - const endFetch = caches.match('/shell_bottom'); - const middleFetch = fetch(url).then(response => { - if (!response.ok && response.status === 404) { - return caches.match('/404.html'); - } - if (!response.ok && response.status != 404) { - return caches.match('/500.html'); - } - return response; - }).catch(err => caches.match('/offline.html')); + function pushStream(stream) { + const reader = stream.getReader(); + return reader.read().then(function process(result) { + if (result.done) return; + controller.enqueue(result.value); + return reader.read().then(process); + }); + } + startFetch + .then(response => pushStream(response.body)) + .then(() => middleFetch) + .then(response => pushStream(response.body)) + .then(() => endFetch) + .then(response => pushStream(response.body)) + .then(() => controller.close()); + }) - function pushStream(stream) { - const reader = stream.getReader(); - return reader.read().then(function process(result) { - if (result.done) return; - controller.enqueue(result.value); - return reader.read().then(process); - }); - } - startFetch - .then(response => pushStream(response.body)) - .then(() => middleFetch) - .then(response => pushStream(response.body)) - .then(() => endFetch) - .then(response => pushStream(response.body)) - .then(() => controller.close()); } });