Skip to content

Commit

Permalink
docs(pwa): serve SPA index, don't cache static pages (#15116)
Browse files Browse the repository at this point in the history
resolves #15089
  • Loading branch information
ElijahKotyluk committed May 20, 2022
1 parent cfdb9d4 commit 45818a5
Showing 1 changed file with 18 additions and 7 deletions.
25 changes: 18 additions & 7 deletions packages/docs/src/service-worker.js
@@ -1,16 +1,23 @@
// Imports
import { precacheAndRoute, matchPrecache } from 'workbox-precaching'
import { registerRoute, setDefaultHandler, setCatchHandler } from 'workbox-routing'
import { NetworkOnly, CacheFirst } from 'workbox-strategies'
import { matchPrecache, precacheAndRoute } from 'workbox-precaching'
import { registerRoute, setCatchHandler, setDefaultHandler } from 'workbox-routing'
import { NetworkOnly } from 'workbox-strategies'

precacheAndRoute(self.__WB_MANIFEST)

const cacheFirst = new CacheFirst()
const networkOnly = new NetworkOnly()

registerRoute(
({ url, request }) => url.origin === self.location.origin && request.destination !== 'document',
cacheFirst
({ url, request }) => url.origin === self.location.origin && request.destination === 'document',
async options => {
const { url } = options
const fallback = await getFallbackDocument(url)
if (fallback) {
console.log(`[SW] serving fallback for ${url.pathname}`)
}

return fallback ?? networkOnly.handle(options)
}
)

setDefaultHandler(networkOnly)
Expand All @@ -20,7 +27,7 @@ setCatchHandler(async ({ url, request }) => {
url.origin === self.location.origin &&
request.destination === 'document'
) {
return matchPrecache(url.pathname.startsWith('/eo-UY/') ? '_crowdin.html' : '/_fallback.html')
return getFallbackDocument(url)
}

return Response.error()
Expand All @@ -29,3 +36,7 @@ setCatchHandler(async ({ url, request }) => {
self.addEventListener('message', event => {
if (event.data === 'sw:update') self.skipWaiting()
})

function getFallbackDocument (url) {
return matchPrecache(url.pathname.startsWith('/eo-UY/') ? '_crowdin.html' : '/_fallback.html')
}

0 comments on commit 45818a5

Please sign in to comment.