我正在学习如何使用服务工作者,我的问题是当第一次加载页面时点击按钮fetch()
某些文件时没有触发任何fetch
事件,但是手动刷新页面然后再次单击该按钮后,fetch
事件将按预期触发
请指导如何解决此问题 感谢
Chrome:60
服务worker.js
self.addEventListener('install', event => {
event.waitUntil(
caches.open('XXX')
.then(cache => {
cache.allAll([ ... ])
})
)
})
self.addEventListener('activate', event => {
console.log('ready')
})
self.addEventListener('fetch', event => {
console.log('fetch')
})
的index.html
<body>
<button id="btn" class="button">Click</button>
<script>
(() => {
document.getElementById('btn').addEventListener('click', () => {
fetch(' ... ')
.then(res => {
return res.json()
})
.then(res => {
console.log(res)
})
})
if (!('serviceWorker' in navigator)) {
console.log('Service Worker is not supported')
return
}
navigator.serviceWorker.register('/service-worker.js')
.then((registration) => {
console.log('Sevice Worker has been registered')
})
})()
</script>
</body>
答案 0 :(得分:1)
你可能需要self.clients.claim()来尽快激活service-worker。
self.addEventListener('activate', function(event) {
event.waitUntil(self.clients.claim());
});