Skip to content

Instantly share code, notes, and snippets.

@Maxiviper117
Created February 19, 2025 18:21
Show Gist options
  • Select an option

  • Save Maxiviper117/54faab0e48b665bd757033384e803296 to your computer and use it in GitHub Desktop.

Select an option

Save Maxiviper117/54faab0e48b665bd757033384e803296 to your computer and use it in GitHub Desktop.
Service Worker-based caching of external images in a Svelte app for offline support.

Caching External Images in Svelte using Service Workers

This guide explains how to cache external images used in <img> elements in a Svelte application using a service worker. This improves performance and enables offline availability of images.


1. Register the Service Worker in Svelte

In your main Svelte component (e.g., src/routes/+layout.svelte), register the service worker:

<script>
  if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/service-worker.js')
      .then(() => {
        console.log('Service Worker registered successfully.');
      })
      .catch((error) => {
        console.error('Service Worker registration failed:', error);
      });
  }
</script>

2. Create the Service Worker File

Create a file named service-worker.js inside the static/ or public/ directory of your Svelte project:

self.addEventListener('install', (event) => {
  console.log('Service Worker installing.');
});

self.addEventListener('activate', (event) => {
  console.log('Service Worker activating.');
});

self.addEventListener('fetch', (event) => {
  // Check if the request is for an image
  if (event.request.destination === 'image') {
    event.respondWith(
      caches.open('image-cache').then((cache) => {
        return cache.match(event.request).then((cachedResponse) => {
          if (cachedResponse) {
            // Return cached image if available
            return cachedResponse;
          }
          // Fetch the image from the network
          return fetch(event.request).then((networkResponse) => {
            // Cache the fetched image for future use
            cache.put(event.request, networkResponse.clone());
            return networkResponse;
          });
        });
      })
    );
  } else {
    // For non-image requests, proceed as usual
    event.respondWith(fetch(event.request));
  }
});

3. Where Are the Images Cached?

  • Images are stored in the Cache Storage API, which is part of the browser’s IndexedDB system.
  • You can view them in Developer Tools:
    • Chrome: F12ApplicationStorageCache Storage
    • Firefox: F12StorageCache Storage
  • You can also inspect cached images programmatically:
caches.open('image-cache').then(cache => {
  cache.keys().then(keys => console.log(keys));
});

4. How to Clear the Cache?

Via DevTools:

  • Open DevToolsApplicationCache Storage
  • Right-click on image-cache and Delete it

Programmatically:

caches.delete('image-cache').then(() => console.log("Cache cleared"));

5. Summary

✅ Images are stored in Cache Storage for improved performance and offline access. ✅ The service worker intercepts image requests and caches them. ✅ Cached images persist across sessions unless manually cleared. ✅ You can inspect and clear the cache via DevTools or programmatically.

This setup helps optimize your Svelte application by reducing unnecessary image loads!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment