You know the feeling: you saw a cool website or read an interesting article the other day, and you’d like to check back on it, or maybe you’re with some people that you’d like to share it with. But what’s this? You don’t have any phone signal, and the WiFi connection is spotty at best – if there is one at all! You attempt to open the page, but try as you might, the loading spinner just keeps on spinning…
gatsby-plugin-offline, that’s a thing of the past. Install the plugin in an existing Gatsby site using npm or Yarn, add it to your
gatsby-config.js, and your site will instantly gain offline support without any additional configuration needed. (Read full instructions on how to add offline support with a service worker
.) Now, whenever someone visits a page on your site, that page will be available later without an internet connection, along with any other pages which have been preloaded in the background.
gatsby-plugin-offline version 3 was released, adding some exciting new features such as the ability to pre-cache a customized set of pages. It also introduced some under-the-hood changes, the most notable being a major version upgrade of Workbox, the library which powers the core functionality of
So, how does the service worker detect that JS is disabled, given that the client can’t use JS to communicate this to the worker? Back to an earlier point: we can also communicate to the service worker using data contained within a request, such as its URL. So, if we request a specially formatted URL, and “catch” this request from within the service worker, we can tell it that JS is disabled.
How does this work in practice? Firstly, the service worker keeps track of which page was requested last. Within the offline shell, we include a
noscript tag in the head, inside which is a
meta tag that specifies an immediate redirect to the URL
/.gatsby-plugin-offline:api=disableOfflineShell&redirect=true. The service worker then “catches” this request, disables the offline shell, and then sends a
Location header in its response which sends the browser back to the initially requested page.
If you want to try out this feature for yourself, add the latest
gatsby-plugin-offline to an existing site, or use the Gatsby CLI to run
gatsby new my-blog gatsby-starter-blog and create a new site which includes the plugin out-of-the-box. Find any problems? Let us know!