Skip to content

feat: e.skipWaiting() in sw-update event #462

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

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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
42 changes: 42 additions & 0 deletions lib/app/SWUpdateEvent.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
export default class SWUpdateEvent {
constructor (registration) {
Object.defineProperty(this, 'registration', {
value: registration,
configurable: true,
writable: true
})
}

/**
* Check if the new service worker exists or not.
*/
update () {
return this.registration.update()
}

/**
* Activate new service worker to work 'location.reload()' with new data.
*/
skipWaiting () {
const worker = this.registration.waiting
if (!worker) {
return Promise.resolve()
}

console.log('[vuepress:sw] Doing worker.skipWaiting().')
return new Promise((resolve, reject) => {
const channel = new MessageChannel()

channel.port1.onmessage = (event) => {
console.log('[vuepress:sw] Done worker.skipWaiting().')
if (event.data.error) {
reject(event.data.error)
} else {
resolve(event.data)
}
}

worker.postMessage({ type: 'skip-waiting' }, [channel.port2])
})
}
}
9 changes: 5 additions & 4 deletions lib/app/clientEntry.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/* global BASE_URL, GA_ID, ga, SW_ENABLED */

import { createApp } from './app'
import SWUpdateEvent from './SWUpdateEvent'
import { register } from 'register-service-worker'

const { app, router } = createApp()
Expand Down Expand Up @@ -41,13 +42,13 @@ router.onReady(() => {
console.log('[vuepress:sw] Service worker is active.')
app.$refs.layout.$emit('sw-ready')
},
cached () {
cached (registration) {
console.log('[vuepress:sw] Content has been cached for offline use.')
app.$refs.layout.$emit('sw-cached')
app.$refs.layout.$emit('sw-cached', new SWUpdateEvent(registration))
},
updated () {
updated (registration) {
console.log('[vuepress:sw] Content updated.')
app.$refs.layout.$emit('sw-updated')
app.$refs.layout.$emit('sw-updated', new SWUpdateEvent(registration))
},
offline () {
console.log('[vuepress:sw] No internet connection found. App is running in offline mode.')
Expand Down
7 changes: 6 additions & 1 deletion lib/build.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,11 +81,16 @@ module.exports = async function build (sourceDir, cliOptions = {}) {
if (options.siteConfig.serviceWorker) {
logger.wait('\nGenerating service worker...')
const wbb = require('workbox-build')
wbb.generateSW({
await wbb.generateSW({
swDest: path.resolve(outDir, 'service-worker.js'),
globDirectory: outDir,
globPatterns: ['**\/*.{js,css,html,png,jpg,jpeg,gif,svg,woff,woff2,eot,ttf,otf}']
})
await fs.writeFile(
Copy link

Choose a reason for hiding this comment

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

Copy link
Member Author

Choose a reason for hiding this comment

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

Thank you for the suggestion.

I compared it and the current code, I didn't feel that the option improves the build steps much. We need the following steps with the option:

  1. Copy the service-worker/*.js files to outDir manually. (Webpack doesn't handle the files for service worker because Workbox requires the files Webpack generated.)
  2. Give the path to service-worker/*.js files to the importScripts option.

Step 1 is the same step as the current appending step essentially. Plus, there are some concerns:

  1. the importScripts option makes extra HTTPS requests.
  2. Chrome has a bug that overlooks the changes of imported scripts (chromium#648295). This implies the change of the service-worker/*.js files will not trigger to update service worker's caches.

path.resolve(outDir, 'service-worker.js'),
await fs.readFile(path.resolve(__dirname, 'service-worker/skip-waiting.js'), 'utf8'),
{ flag: 'a' }
)
}

// DONE.
Expand Down
12 changes: 12 additions & 0 deletions lib/service-worker/skip-waiting.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
addEventListener('message', event => {
const replyPort = event.ports[0]
const message = event.data
if (replyPort && message && message.type === 'skip-waiting') {
event.waitUntil(
self.skipWaiting().then(
() => replyPort.postMessage({ error: null }),
error => replyPort.postMessage({ error })
)
)
}
})
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@
"portfinder": "^1.0.13",
"postcss-loader": "^2.1.5",
"prismjs": "^1.13.0",
"register-service-worker": "^1.2.0",
"register-service-worker": "^1.3.0",
"semver": "^5.5.0",
"stylus": "^0.54.5",
"stylus-loader": "^3.0.2",
Expand Down
2 changes: 1 addition & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -7022,7 +7022,7 @@ regexpu-core@^4.1.3, regexpu-core@^4.1.4:
unicode-match-property-ecmascript "^1.0.3"
unicode-match-property-value-ecmascript "^1.0.1"

register-service-worker@^1.2.0:
register-service-worker@^1.3.0:
version "1.3.0"
resolved "https://registry.yarnpkg.com/register-service-worker/-/register-service-worker-1.3.0.tgz#02a0b7c40413b3c5ed1d801d764deb3aab1c3397"

Expand Down