I'm new to Service Worker, I tried to write some code to learn how to use Service Worker in My Next.js Application but found some problems with fetch event handler, for some reason fetch event handler doesn't run when registering the service worker for the first time but when i just refresh the page the event handler works just fine and i don't know why , this my app's public folder structure:
/public
/assets
/icons
manifest.json
service-worker.js
service-worker-registration.js
manifest.js:
{
"name": "FakeHulu",
"short_name": "FakeHulu",
"description": "My Own version of Hulu",
"icons": [
{
"src": "/icons/manifest-icon-192.maskable.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "any"
}, ...
],
"theme_color": "#ffffff",
"background_color": "#ffffff",
"start_url": "/",
"display": "fullscreen",
"orientation": "portrait"
}
service-worker-registration.js:
if("serviceWorker" in navigator){
window.navigator.serviceWorker.register("/service-worker.js", { scope: '/' }).then(sw => console.log("serviceWorker Supported and register"))
}
service-worker.js:
self.addEventListener("install" , evt => {
evt.waitUntil(caches.open("main_cache").then(cache => cache.addAll(["/", "/something"])));
self.skipWaiting();
});
self.addEventListener("activate" , evt => {
console.log(evt);
clients.claim();
});
self.addEventListener("fetch" , evt => {
console.log(evt);
});
On your fist load the order of operation is this:
Notice that there's no fetch() handler to run when your client and service worker are downloaded because the service worker hasn't been installed yet.
On reload the order is this:
Fetch() handler in the existing service worker intercepts the request and decides whether to retrieve the requested resource from a local resource or from the network.