我正在阅读ServiceWorker https://bitsofco.de/the-service-worker-lifecycle/。 我很困惑:
如果activate事件中有一个event.waitUntil()方法,则只有在解决Promise之后,激活才能成功。如果Promise被拒绝,则激活事件失败,并且Service Worker变得多余。
我所做的如下: index.html:
<!DOCTYPE html>
<html>
<head>
<title>Google WorkBox</title>
<meta name="viewport" content="width=device-width,initial-scale=1.0">
</head>
<body>
<script>
// Check that service workers are registered
if ('serviceWorker' in navigator) {
// Use the window load event to keep the page load performant
window.addEventListener('load', () => {
navigator.serviceWorker.register('sw-fetch.js?v=' + 1).then((registration) => {
var sw = null, state;
if(registration.installing) {
sw = registration.installing;
state = 'installing';
} else if(registration.waiting) {
sw = registration.waiting;
state = 'installed'
} else if(registration.active) {
sw = registration.active;
state = 'activated'
}
state && console.log(`sw state is ${state}`);
if(sw) {
sw.onstatechange = function() {
console.log(`sw state is ${sw.state}`);
}
}
});
});
}
</script>
</body>
</html>
sw.js:
self.addEventListener('activate', (event) => {
event.waitUntil(new Promise((resolve, reject) =>{
setTimeout(() => {
reject('Reject activate')
}, 2000)
}))
})
如您所见,通过兑现承诺,ServiceWorker被激活。