I'm learning how to use service worker, my problem is that when clicking the button to fetch()
some file when the page is loaded for first time didn't fire any fetch
event, but after manually refresh the page then clicking the button again, the fetch
event get fired as expected
Please guide how to fix this thanks
Chrome: 60
service-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>