Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(gatsby-plugin-offline): reload when missing resources and SW was updated + add "onServiceWorkerUpdateReady" API #10432

Merged
merged 18 commits into from
Jan 28, 2019
Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions docs/docs/add-offline-support-with-a-service-worker.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,10 @@ Note: Service worker registers only in production builds (`gatsby build`).

### Displaying a message when a service worker updates

To display a custom message once your service worker finds an update, you can use the [`onServiceWorkerUpdateFound`](/docs/browser-apis/#onServiceWorkerUpdateFound) browser API in your `gatsby-browser.js` file. The following code will display a confirm prompt asking the user whether they would like to refresh the page when an update is found:
To display a custom message once your service worker finds an update, you can use the [`onServiceWorkerUpdateReady`](/docs/browser-apis/#onServiceWorkerUpdateReady) browser API in your `gatsby-browser.js` file. The following code will display a confirm prompt asking the user whether they would like to refresh the page when an update is found:

```javascript:title=gatsby-browser.js
exports.onServiceWorkerUpdateFound = () => {
exports.onServiceWorkerUpdateReady = () => {
const answer = window.confirm(
`This application has been updated. ` +
`Reload to display the latest version?`
Expand Down
1 change: 0 additions & 1 deletion packages/gatsby-plugin-offline/.gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
/*.js
!index.js
!sw-append.js
yarn.lock
7 changes: 5 additions & 2 deletions packages/gatsby-plugin-offline/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
"dependencies": {
"@babel/runtime": "^7.0.0",
"cheerio": "^1.0.0-rc.2",
"cpx": "^1.5.0",
"idb-keyval": "^3.1.0",
"lodash": "^4.17.10",
"workbox-build": "^3.6.3"
Expand All @@ -34,8 +35,10 @@
},
"repository": "https://github.com/gatsbyjs/gatsby/tree/master/packages/gatsby-plugin-offline",
"scripts": {
"build": "babel src --out-dir . --ignore **/__tests__",
"build": "npm run build:src && npm run build:sw-append",
"build:src": "babel src --out-dir . --ignore **/__tests__",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we need to ignore sw-append.js here? for builds it probably doesn't matter - it will be overwritten by cpx in next step, but while watching, babel will try to compile it?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ah yep, that's a good point - need to fix that

"build:sw-append": "cpx -v src/sw-append.js .",
"prepare": "cross-env NODE_ENV=production npm run build",
"watch": "babel -w src --out-dir . --ignore **/__tests__"
"watch": "npm run build:sw-append -- --watch & npm run build:src -- --watch"
}
}
3 changes: 3 additions & 0 deletions packages/gatsby-plugin-offline/src/gatsby-browser.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ exports.onServiceWorkerActive = ({
getResourceURLsForPathname,
serviceWorker,
}) => {
// reset whitelisted paths
serviceWorker.active.postMessage({ gatsbyApi: `resetWhitelist` })

// grab nodes from head of document
const nodes = document.querySelectorAll(`
head > script[src],
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,20 +13,23 @@ const navigationRoute = new workbox.routing.NavigationRoute(({ event }) => {
const cacheName = workbox.core.cacheNames.precache

return caches.match(offlineShell, { cacheName }).then(cachedResponse => {
if (!cachedResponse) {
return fetch(offlineShell).then(response => {
if (response.ok) {
return caches.open(cacheName).then(cache =>
// Clone is needed because put() consumes the response body.
cache.put(offlineShell, response.clone()).then(() => response)
)
} else {
return fetch(event.request)
}
})
}

return cachedResponse
if (cachedResponse) return cachedResponse

console.error(
`The offline shell (${offlineShell}) was not found ` +
`while attempting to serve a response for ${pathname}`
)

return fetch(offlineShell).then(response => {
if (response.ok) {
return caches.open(cacheName).then(cache =>
// Clone is needed because put() consumes the response body.
cache.put(offlineShell, response.clone()).then(() => response)
)
} else {
return fetch(event.request)
}
})
})
}

Expand Down
2 changes: 2 additions & 0 deletions packages/gatsby/cache-dir/ensure-resources.js
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,8 @@ class EnsureResources extends React.Component {

render() {
if (!this.hasResources(this.state.pageResources) && isInitialRender) {
window.___failedResources = true
pieh marked this conversation as resolved.
Show resolved Hide resolved

// prevent hydrating
throw new Error(`Missing resources for ${this.state.location.pathname}`)
}
Expand Down
10 changes: 0 additions & 10 deletions packages/gatsby/cache-dir/navigation.js
Original file line number Diff line number Diff line change
Expand Up @@ -65,16 +65,6 @@ const navigate = (to, options = {}) => {
pathname = parsePath(to).pathname
}

// If we had a service worker update, no matter the path, reload window and
// reset the pathname whitelist
if (window.GATSBY_SW_UPDATED) {
const { controller } = navigator.serviceWorker
controller.postMessage({ gatsbyApi: `resetWhitelist` })

window.location = pathname
return
}

// Start a timer to wait for a second before transitioning and showing a
// loader in case resources aren't around yet.
const timeoutId = setTimeout(() => {
Expand Down
10 changes: 8 additions & 2 deletions packages/gatsby/cache-dir/register-service-worker.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,14 @@ if (
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and the fresh content will
// have been added to the cache.
// We set a flag so Gatsby Link knows to refresh the page on next navigation attempt
window.GATSBY_SW_UPDATED = true
// We call the onServiceWorkerUpdateReady API so users can show update prompts.
apiRunner(`onServiceWorkerUpdateReady`, { serviceWorker: reg })

// If resources failed for the current page, reload.
if (window.___failedResources) {
console.log(`resources failed, SW updated - reloading`)
pieh marked this conversation as resolved.
Show resolved Hide resolved
window.location.reload()
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a "Content is cached for offline use." message.
Expand Down
8 changes: 8 additions & 0 deletions packages/gatsby/src/utils/api-browser-docs.js
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,14 @@ exports.onServiceWorkerInstalled = true
*/
exports.onServiceWorkerUpdateFound = true

/**
* Inform plugins when a service worker has been updated in the background
* and the page is ready to reload to apply changes.
* @param {object} $0
* @param {object} $0.serviceWorker The service worker instance.
*/
exports.onServiceWorkerUpdateReady = true

/**
* Inform plugins when a service worker has become active.
* @param {object} $0
Expand Down
Loading