Skip to content

Commit 1eb1190

Browse files
author
pooya parsa
committed
feat(workbox): make plugin fully asynchronous
1 parent 89c1a1d commit 1eb1190

File tree

2 files changed

+24
-24
lines changed

2 files changed

+24
-24
lines changed

docs/modules/workbox.md

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,18 @@ workbox: {
2020

2121
## Workbox Window
2222

23-
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`).
23+
This module uses [workbox-window](https://developers.google.com/web/tools/workbox/modules/workbox-window) to register and communicate with workbox service worker.
24+
See docs for more information about use cases.
2425

25-
See [workbox-window](https://developers.google.com/web/tools/workbox/modules/workbox-window) docs for more information about use cases.
26+
As service worker is registered in background, to access instance you have to await on a promise:
27+
28+
```js
29+
const workbox = await window.$workbox
30+
31+
if (workbox) {
32+
// Service worker is available
33+
}
34+
```
2635

2736
## Options
2837

Lines changed: 13 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,18 @@
1-
function onError(error) {<% if (options.dev) { %>console.error('Error registering workbox:', error) <% } %>}
2-
3-
export default function (ctx, inject) {
4-
let workbox = {}
1+
async function register() {
2+
if (!'serviceWorker' in navigator) {
3+
throw new Error('serviceWorker is not supported in current browser!')
4+
}
55

6-
try {
7-
// workbox-window does not detects unsupported browsers
8-
if (!'serviceWorker' in navigator) {
9-
throw new Error('serviceWorker is not supported in current browser!')
10-
}
6+
const { Workbox } = await import('workbox-cdn/workbox/workbox-window.<%= options.dev ? 'dev' : 'prod' %>.es5.mjs')
117

12-
// Use require() instead of import() to prevent creating extra chunk
13-
// Use es5 version to prevent crashing older browsers while parsing bundle
14-
const { Workbox } = require('workbox-cdn/workbox/workbox-window.<%= options.dev ? 'dev' : 'prod' %>.es5.mjs')
8+
const workbox = new Workbox('<%= options.swURL %>', {
9+
scope: '<%= options.swScope %>'
10+
})
1511

16-
workbox = new Workbox('<%= options.swURL %>', {
17-
scope: '<%= options.swScope %>'
18-
})
12+
await workbox.register()
1913

20-
workbox.register().catch(onError)
21-
} catch (error) {
22-
onError(error)
23-
}
24-
25-
// Inject as $workbox
26-
inject('workbox', workbox)
14+
return workbox
2715
}
16+
17+
window.$workbox = register()
18+
.catch(error => {<% if (options.dev) { %> console.error('Error registering workbox:', error) <% } %>})

0 commit comments

Comments
 (0)