why to use indexeddb instead of cache api for dynamic content
Asked Answered
B

1

15

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?

Breadroot answered 14/2, 2020 at 11:22 Comment(0)
M
17

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);
Mcallister answered 15/12, 2020 at 18:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.