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.
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>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));
}
});- 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:
F12→Application→Storage→Cache Storage - Firefox:
F12→Storage→Cache Storage
- Chrome:
- You can also inspect cached images programmatically:
caches.open('image-cache').then(cache => {
cache.keys().then(keys => console.log(keys));
});- Open DevTools →
Application→Cache Storage - Right-click on
image-cacheand Delete it
caches.delete('image-cache').then(() => console.log("Cache cleared"));✅ 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!