Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why to use indexeddb instead of cache api for dynamic content

I am using service worker and precache assets in install event.

I also have fetch listener which intercepts requests and caches then at runtime dynamically. I know that people say to use indexeddb for dynamic content such as json data and possibly images.

Question: Why isn't it a good practice to use cache API for that json data too even though it's request/response storage?

The reason I am asking this is because I tried the following: I have index.html and main.js as precached in install event and in main.js I have axios request which returns some json and puts it in index.html. If I use dynamic caching which means when the request to that json api endpoint gets made, it goes first to my service worker, which gets the response and puts it into cache. Then I tested that and when refreshed the page in offline mode, I still got the same result (json data put in index.html accordingly).

So I guess even though Cache API store request/response, it still worked for json endpoint api urls flawlessly.

Any good idea why to prefer indexeddb over cache API while using service worker?

like image 420
Nika Kurashvili Avatar asked Feb 14 '20 11:02

Nika Kurashvili


1 Answers

It's perfectly fine to cache JSON data using the Cache Storage API, as an alternative to using IndexedDB. I would expect similar performance characteristics, and in both cases you could read/write the data from either the service worker or window context.

It would be slightly more awkward to use the Cache Storage API if you have JSON data that isn't already associated with a Response object, or that doesn't have a "real" request URL, since you'll have to effectively "fake" them. But that's not particularly hard to do:

const data = {
  // some data
};
const jsonString = JSON.stringify(data);

const jsonResponse = new Response(jsonString, {
  headers: {
    'content-type': 'application/json',
  },
});
const cache = await caches.open('json-cache');
await cache.put('/some-json-url', jsonResponse);
like image 190
Jeff Posnick Avatar answered Oct 07 '22 02:10

Jeff Posnick