Cache Storage
Cache Storage – regular caching for Network data
Cache Storage is a browser-provided API that allows JavaScript to store network responses for future use. This is particularly useful for offline applications and Progressive Web App (PWA) development.
Unlike LocalStorage or SessionStorage, Cache Storage is designed not for simple key-value data, but for caching complete HTTP responses.
caches.open('my-cache').then(cache => {
fetch('/data.json').then(response => {
cache.put('/data.json', response.clone());
});
});
In this example: We open (or create) a cache named my-cache
, then load /data.json
and store it in the cache. response.clone()
is required because a response can only be used once.
caches.match('/data.json').then(response => {
if (response) {
response.json().then(data => {
console.log('Cached data:', data);
});
} else {
console.log('Not found in cache.');
}
});
In this example: We search for /data.json
in the cache and, if available, use the data without making a network request.
Cache Storage is a powerful tool for implementing network data caching in browsers. It helps accelerate applications, ensure offline availability, and efficiently manage network resources. If you're developing a PWA or looking to improve performance, Cache Storage is definitely worth using.