Adding Offline Support with Service Workers

Adding offline support with service workers is another way to improve performance, particularly because service worker usage is a PWA requirement. The gatsby-plugin-offline plugin automates the process of transforming a Gatsby site into an offline-first implementation that is resistant to inconsistent network conditions with the help of a service worker.

Service workers, in short, are scripts executed in the background by browsers that are distinct from logic run in the web page itself. In spotty network conditions, service workers can provide a better user experience in addition to supporting common features such as push notifications and synchronization of assets in the background.

To install the gatsby-plugin-offline plugin, execute the following command:

$ npm install gatsby-plugin-offline

Then, add the plugin to your Gatsby configuration file:

// gatsby-config.js
{
  plugins: [
    {
      resolve: `gatsby-plugin-manifest`,
      options: {
        // ...
      }
    },
    `gatsby-plugin-offline`,
  ],
}
TIP

Service workers in Gatsby are available only on production-built Gatsby sites (i.e., on gatsby build).

To render a custom message in the browser once your service worker discovers updated content, you can implement one of Gatsby’s Browser APIs, onServiceWorker​Upda⁠teReady, in gatsby-browser.js. The following code block illustrates an example implementation, displaying a confirmation prompt requesting the user to approve a refresh of the page:

// gatsby-browser.js
export const onServiceWorkerUpdateReady = () => {
  const answer = window.confirm(
    `A new version of this application is available. ` +
    `Refresh to update?`
  )

  if (answer === true) {
    window.location.reload()
  }
}

If you need to add a custom service worker to Gatsby, for example to support a requirement unsupported by the gatsby-plugin-offline plugin, add a file to the static directory named sw.js (per service worker convention) and implement the registerServiceWorker API in gatsby-browser.js as follows:

// gatsby-browser.js
export const registerServiceWorker = () => true

To remove the service worker entirely from your built Gatsby site, use the Gatsby ecosystem plugin gatsby-plugin-remove-serviceworker.

NOTE

For more information about removing a service worker, consult the documentation for the gatsby-plugin-offline plugin. For more information about service workers in general, consult the documentation provided by Google and the Mozilla Developer Network.


Posted

in

,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *