Recently I came across the Cache API. It’s used in Service Workers to prefetch/cache files for your offline web app, but it’s also available outside of workers.
I was looking at using the Cache API to cache generated images, to speed up a WebGL piece, without crashing Safari. Never got around to it, but now I’m looking at it, it’s kinda easy:
To open a cache and save an arbitrary string:
caches.open('SomeCacheName').then(async cache => {
// put something in the cache
await cache.put('SomeKeyName', new Response('Hello world'));
// Get something back out of the cache
const response = await cache.match('SomeKeyName');
const text = await response.text();
console.log(text); // Hello World
});
You can then reopen that cache at any time in the future to fetch your value:
caches.open('SomeCacheName').then(async cache => {
const response = await cache.match('SomeKeyName');
// treat the response object as you would a fetch() response
const text = await response.text();
console.log(text); // Hello World
});
While this example uses strings (retrieved with response.text()
), you can store any number of formats including Blobs and ArrayBuffers. See the Response constructor for ideas.
The benefit of using the standard old browser cache is that you can store a LOT of data. My Mac reports the following:
navigator.storage.estimate().then((estimate) => {
console.log('percent', (
(estimate.usage / estimate.quota) *
100
).toFixed(2));
// percent 0.00
console.log('quota', (estimate.quota / 1024 / 1024).toFixed(2) + "MB");
// quota 10240.00MB
});
That’s 10 gigabytes of storage available. To be fair, not everyone will have that much space, but you get the idea.
It also needs to be cleaned up manually, otherwise it will sit in the cache permanently taking up space (unless the cache is cleared). The MDN page says:
The browser does its best to manage disk space, but it may delete the
Cache
storage for an origin. The browser will generally delete all of the data for an origin or none of the data for an origin.
I haven’t used this in production yet, but it seems to work fine. And browser support looks good. So let me know if this is useful.
For more reading, check out the MDN Cache API.