Skip to content

Commit

Permalink
Allow register to be called after onload event (#33)
Browse files Browse the repository at this point in the history
* Allow `register` to be called after `onload` event

It's not possible to register service-worker on demand right now.

* fix: fix compatibility with IE11

Co-authored-by: Haoqun Jiang <haoqunjiang@gmail.com>
  • Loading branch information
cainrus and sodatea committed Mar 10, 2020
1 parent 16d2a77 commit 5f96e33
Showing 1 changed file with 12 additions and 1 deletion.
13 changes: 12 additions & 1 deletion src/index.js
Expand Up @@ -15,6 +15,17 @@ const isLocalhost = () => Boolean(
)
)

let waitWindowLoad
// Typically, a browser that supports `serviceWorker` should also have supported
// `Promise`. But as this package can be used in environments without service
// worker support (in that case it would do nothing), there's a chance that
// `Promise` does not exist. So we must check for its existence first.
if (typeof Promise !== 'undefined') {
waitWindowLoad = new Promise(resolve => window.addEventListener('load', resolve))
} else {
waitWindowLoad = { then: (cb) => window.addEventListener('load', cb) }
}

export function register (swUrl, hooks = {}) {
const { registrationOptions = {}} = hooks
delete hooks.registrationOptions
Expand All @@ -26,7 +37,7 @@ export function register (swUrl, hooks = {}) {
}

if ('serviceWorker' in navigator) {
window.addEventListener('load', () => {
waitWindowLoad.then(() => {
if (isLocalhost()) {
// This is running on localhost. Lets check if a service worker still exists or not.
checkValidServiceWorker(swUrl, emit, registrationOptions)
Expand Down

0 comments on commit 5f96e33

Please sign in to comment.