Page 3: Implementing Caching Strategy & Push Notifications

3. Implementing Caching Strategy & Push Notifications

We implement one of the most common caching strategies, Cache-first, Network-fallback, to serve content even when the user is offline.

3.1. Implementing Caching Strategy (fetch event)

Use the fetch event handler to intercept requests, check the cache first, and fall back to the network if the resource is not found.

self.addEventListener('fetch', (event) => {
  event.respondWith(
    caches.match(event.request) // 1. Look in the cache first
      .then((response) => {
        if (response) {
          return response; // 2. If present, return the cached response
        }
        return fetch(event.request); // 3. If not in cache, request from the network
      })
  );
});

3.2. Pre-caching Static Assets (install event)

Pre-cache the core files of your App Shell structure during the Service Worker\'s installation phase to ensure instant loading.

const urlsToCache = [
  '/',
  '/index.html',
  '/styles.css',
  '/main.js'
];

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME)
      .then((cache) => {
        console.log('Opened cache and pre-caching shell assets');
        return cache.addAll(urlsToCache);
      })
  );
});