Skip to content
Permalink
Browse files
feat(workbox): make plugin fully asynchronous
  • Loading branch information
pooya parsa committed Mar 17, 2019
1 parent 89c1a1d commit 1eb11905a7499cb3b886265969a939d55eb53ca1
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 24 deletions.
@@ -20,9 +20,18 @@ workbox: {

## Workbox Window

A global `$workbox` service is injected to the application, which can be used either by plugins (via `context.app.$workbox`) or pages (via `this.$workbox`).
This module uses [workbox-window](https://developers.google.com/web/tools/workbox/modules/workbox-window) to register and communicate with workbox service worker.
See docs for more information about use cases.

See [workbox-window](https://developers.google.com/web/tools/workbox/modules/workbox-window) docs for more information about use cases.
As service worker is registered in background, to access instance you have to await on a promise:

```js
const workbox = await window.$workbox
if (workbox) {
// Service worker is available
}
```

## Options

@@ -1,27 +1,18 @@
function onError(error) {<% if (options.dev) { %>console.error('Error registering workbox:', error) <% } %>}

export default function (ctx, inject) {
let workbox = {}
async function register() {
if (!'serviceWorker' in navigator) {
throw new Error('serviceWorker is not supported in current browser!')
}

try {
// workbox-window does not detects unsupported browsers
if (!'serviceWorker' in navigator) {
throw new Error('serviceWorker is not supported in current browser!')
}
const { Workbox } = await import('workbox-cdn/workbox/workbox-window.<%= options.dev ? 'dev' : 'prod' %>.es5.mjs')
// Use require() instead of import() to prevent creating extra chunk
// Use es5 version to prevent crashing older browsers while parsing bundle
const { Workbox } = require('workbox-cdn/workbox/workbox-window.<%= options.dev ? 'dev' : 'prod' %>.es5.mjs')
const workbox = new Workbox('<%= options.swURL %>', {
scope: '<%= options.swScope %>'
})
workbox = new Workbox('<%= options.swURL %>', {
scope: '<%= options.swScope %>'
})
await workbox.register()
workbox.register().catch(onError)
} catch (error) {
onError(error)
}
// Inject as $workbox
inject('workbox', workbox)
return workbox
}
window.$workbox = register()
.catch(error => {<% if (options.dev) { %> console.error('Error registering workbox:', error) <% } %>})

0 comments on commit 1eb1190

Please sign in to comment.