Skip to content

Commit

Permalink
feat(workbox): make plugin fully asynchronous
Browse files Browse the repository at this point in the history
  • Loading branch information
pooya parsa committed Mar 17, 2019
1 parent 89c1a1d commit 1eb1190
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 24 deletions.
13 changes: 11 additions & 2 deletions docs/modules/workbox.md
Expand Up @@ -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

Expand Down
35 changes: 13 additions & 22 deletions packages/workbox/templates/sw.register.js
@@ -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.