Gatsby Plugin Offline
Adds drop-in support for making a Gatsby site work offline and more resistant to bad network connections.
20th July 2022
Time to read: 1 min
Intro
Adds drop-in support for making a Gatsby site work offline and more resistant to bad network connections. It uses Workbox Build to create a service worker for the site and loads the service worker into the client.
If you're using this plugin with gatsby-plugin-manifest
(recommended) this
plugin should be listed after that plugin so the manifest file can be included
in the service worker.
Install
npm install gatsby-plugin-offline
Add to gatsby-config.js
plugins array after gatsby-plugin-manifest
`gatsby-plugin-offline`,
Register Service Worker
// gatsby-browser.js
export const registerServiceWorker = () => true
export const onServiceWorkerUpdateReady = () => {
const answer = window.confirm(
`This application has been updated. ` +
`Reload to display the latest version?`
)
if (answer === true) {
window.location.reload()
}
}
Available options
In gatsby-plugin-offline
3.x, the following options are available:
precachePages
lets you specify pages whose resources should be precached by the service worker, using an array of globs. For example:plugins: [ { resolve: `gatsby-plugin-offline`, options: { precachePages: [`/about-us/`, `/projects/*`], }, }, ]
Note: while essential resources of specified pages will be precached, such as JavaScript and CSS, non-essential resources such as fonts and images will not be included. Instead, these will be cached at runtime when a user visits a given page that includes these resources.
appendScript
lets you specify a file to be appended at the end of the generated service worker (sw.js
). For example:plugins: [ { resolve: `gatsby-plugin-offline`, options: { appendScript: require.resolve(`src/custom-sw-code.js`), }, }, ]
// src/custom-sw-code.js // show a notification after 15 seconds (the notification // permission must be granted first) setTimeout(() => { self.registration.showNotification("Hello, world!") }, 15000) // register a custom navigation route const customRoute = new workbox.routing.NavigationRoute(({ event }) => { // ... }) workbox.routing.registerRoute(customRoute)
debug
specifies whether Workbox should show debugging output in the browser console at runtime. When undefined, defaults to showing debug messages onlocalhost
only.workboxConfig
allows you to override the default Workbox options - see Overriding Workbox configuration. For example:plugins: [ { resolve: `gatsby-plugin-offline`, options: { workboxConfig: { importWorkboxFrom: `cdn`, }, }, }, ]