Middle
How would you implement client-side caching?
sobes.tech AI
Answer from AI
Client-side caching can be implemented in several ways:
- LocalStorage / SessionStorage — for storing data between sessions or within a session.
- IndexedDB — for more complex data structures and larger volumes.
- Service Workers — for intercepting network requests and caching responses, enabling offline work and faster loading.
- HTTP Cache-Control headers — the browser caches resources according to these headers.
Example of using Service Worker for caching:
self.addEventListener('install', event => {
event.waitUntil(
caches.open('v1').then(cache => {
return cache.addAll([
'/',
'/styles.css',
'/script.js',
'/image.png'
]);
})
);
});
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request).then(response => {
return response || fetch(event.request);
})
);
});
This approach allows for quick delivery of cached resources and reduces network load.