Lesson 93 - Service Worker Fetch Event in JavaScript
After registering a service worker, one of its most powerful features is the ability to intercept network requests and control how they are handled.
This is possible through the fetch
event inside the service worker.
It allows us to:
- Serve resources from a cache.
- Update cached resources.
- Create offline experiences.
Listening to Fetch Events
Inside your service worker file (sw.js
), you can listen for the fetch
event using self.addEventListener
.
self.addEventListener('fetch', (event) => {
console.log('Fetch event for:', event.request.url);
});
This will log every network request your app makes once the service worker is active.
Responding to Fetch Events
You can use the event.respondWith()
method to provide a custom response to a fetch request.
Example: Responding with a cached version if available.
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request)
.then(response => {
// Return the cached version if available
if (response) {
return response;
}
// Otherwise, fetch from the network
return fetch(event.request);
})
);
});
Note:
caches.match()
checks all the caches the service worker has access to.
Full Example: Cache First, Network Fallback Strategy
self.addEventListener('fetch', (event) => {
event.respondWith(
caches.match(event.request)
.then(response => {
return response || fetch(event.request)
.then(fetchResponse => {
return caches.open('dynamic-cache').then(cache => {
cache.put(event.request.url, fetchResponse.clone());
return fetchResponse;
});
});
})
.catch(() => {
return caches.match('/fallback.html');
})
);
});
- Try cache first
- If not cached, fetch from network
- Save the new network response in cache
- If everything fails, show a fallback page
Key Points
- The
fetch
event lets service workers intercept HTTP requests. - Use
event.respondWith()
to provide a custom response. - Combine
caches.match()
andfetch()
for offline-first strategies.
Practice Exercise
- Create a basic service worker that:
- Caches an offline fallback page.
- Serves the fallback page if the network is unavailable.