We are thrilled to inform you that Lancecourse is NOW INIT Academy — this aligns our name with our next goals — Read more.

It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for INITAcademy.org.

Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

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() and fetch() 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.