Hi Am facing a wired behavior in service worker. After clearing all the cache load the page service worker loading everything to Cache API. then i went offline and reload the page the page is not getting loaded. I went online and loaded the page again then went offline a load the page this time the page getting loaded correctly. i dont know why this behavior is it anything related to the wait time of service worker how to fix this.
After few debugging i found that my fetch code is not getting executed on very first page load. from second page load onward its getting the hit
my sample application hosted here https://ajeeshc.github.io/#/comments
My service worker file is available in here
complete demo code location here
Please help me out here am really in critical state. I have few reading towards the delay in registering the service worker cause this issue how to fix this ?
below is my service worker registration code.
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('service-worker.js', { scope: './' })
.then(function (registration) {
console.log("Service worker registered - from the 24 ", registration)
registration.addEventListener('updatefound', () => {
newWorker = registration.installing;
newWorker.addEventListener('statechange', () => {
switch (newWorker.state) {
case 'installed':
if (navigator.serviceWorker.controller) {
showUpdateBar();
}
break;
}
});
});
})
.catch(function (err) {
console.log("Service Worker Failes to Register", err)
})
navigator.serviceWorker.addEventListener('message', function (event) {
document.getElementById("cache-generic-msg").style.display = "block";
console.log("Got reply from service worker: " + event.data);
});
let refreshing;
navigator.serviceWorker.addEventListener('controllerchange', function () {
if (refreshing) return;
window.location.reload();
refreshing = true;
});
}
after few research i found what i was missing here. with my code at very first load the service worker not getting registered to client. That y its not able to invoke any fetch event. if you see the application tab you can check the client is registered or not. if it registered you will have the name there else it will be empty
Now how to register the client at first load itself use
self.clients.claim()
Please find the code below
self.addEventListener('activate', (event) => {
console.info('Event: Activate');
event.waitUntil(
self.clients.claim(),
caches.keys().then((cacheNames) => {
return Promise.all(
cacheNames.map((cache) => {
if (cache !== cacheName) {
return caches.delete(cache);
}
})
);
})
);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.