Last active
January 4, 2021 12:13
-
-
Save jeffposnick/5d2e723f283045e59284d6711f2c8a74 to your computer and use it in GitHub Desktop.
Example Workbox plugin that fallsback to a cached HTML page when there's a non-200 OK navigation response.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export class FallbackOnErrorPlugin { | |
constructor(fallbackURL) { | |
this.fallbackURL = fallbackURL; | |
} | |
// This is called whenever there's a network response, | |
// but we want special behavior for non-2xx statuses. | |
fetchDidSucceed({response}) { | |
if (response.ok) { | |
// If it's a 2xx, it can be used as-is. | |
return response; | |
} | |
// This will trigger handlerDidError. | |
throw new Error(`Invalid response status (${response.status})`); | |
} | |
// This callback is new in Workbox v6, and is triggered whenever | |
// an error (including a NetworkError) is thrown when a handler runs. | |
handlerDidError() { | |
return caches.match(this.fallbackURL, { | |
// Use ignoreSearch as a shortcut to work with precached URLs | |
// that have _WB_REVISION parameters. | |
ignoreSearch: true, | |
}); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {registerRoute} from 'workbox-routing'; | |
import {NetworkOnly} from 'workbox-strategies'; | |
import {FallbackOnErrorPlugin} from './fallback-on-error-plugin.js'; | |
registerRoute( | |
// Only trigger this logic for navigation requests for HTML. | |
({request}) => request.mode === 'navigate', | |
// Alternatively, use StaleWhileRevalidate, NetworkFirst, etc. | |
new NetworkOnly({ | |
plugins: [ | |
new FallbackOnErrorPlugin('/fallback.html'), | |
], | |
}), | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment