From 19e9f3ed4b327230fad4ef91bba6caeec0893ec3 Mon Sep 17 00:00:00 2001 From: Michal Piechowiak Date: Thu, 6 Dec 2018 23:37:10 +0100 Subject: [PATCH] fix(gatsby-plugin-offline): gracefully degrade if appshell isn't precached (#10329) If app shell is not in precache (for whatever reason) - try to fetch it. If we fetch successfully - put it in precache for any future requests so we can use happy path again. If we can't fetch app shell - fallback to fetching actual html content of the page. --- packages/gatsby-plugin-offline/src/sw-append.js | 17 ++++++++++++++++- 1 file changed, 16 insertions(+), 1 deletion(-) diff --git a/packages/gatsby-plugin-offline/src/sw-append.js b/packages/gatsby-plugin-offline/src/sw-append.js index 0d6c4a191d467..b209013dd20d8 100644 --- a/packages/gatsby-plugin-offline/src/sw-append.js +++ b/packages/gatsby-plugin-offline/src/sw-append.js @@ -12,7 +12,22 @@ const navigationRoute = new workbox.routing.NavigationRoute(({ event }) => { const offlineShell = `%pathPrefix%/offline-plugin-app-shell-fallback/index.html` const cacheName = workbox.core.cacheNames.precache - return caches.match(offlineShell, { cacheName }) + return caches.match(offlineShell, { cacheName }).then(cachedResponse => { + if (!cachedResponse) { + return fetch(offlineShell).then(response => { + if (response.ok) { + return caches.open(cacheName).then(cache => + // Clone is needed because put() consumes the response body. + cache.put(offlineShell, response.clone()).then(() => response) + ) + } else { + return fetch(event.request) + } + }) + } + + return cachedResponse + }) } return fetch(event.request)