Using indexedDB to Cache Audio Files Not Recommended?

Viewed 1073

I'd like to use indexedDB to store an audio file which I get from my CDN - to improve the users experience, and also do not put such heavy loads onto my CDN. Is this generally recommended for files like mp3? Are there any gotchas?

I've found a few tutorials on storing audio & image in indexedDb, but I also looked for answers on here before, and here somebody says that indexedDB is not generally recommended to store audio files. - Is this true? Unfortunately, the person does not give any further explanation. So if this is true, I'd like to know why.

Thanks a lot.

2 Answers

You can store binary data in IndexedDB but need to be careful for platform limitations.

The main platform limit I know of is described in this Best Practices article by a Google Engineer - the naive approach of storing a Blob type won't work on iOS - you need to convert to an ArrayBuffer using a pair of functions:

function blobToArrayBuffer(blob) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.addEventListener('loadend', (e) => {
      resolve(reader.result);
    });
    reader.addEventListener('error', reject);
    reader.readAsArrayBuffer(blob);
  });
}

function arrayBufferToBlob(buffer, type) {
  return new Blob([buffer], {type: type});
}

Many warnings against storage come from the (incorrect) assumption you have to convert data to base-64 encoded ASCII, which is slow and bloats the amount of spaces needed.

Using indexeddb to store any binary data of any kind is not recommended. It was poorly designed for this use case. That said, it is doable. Anything is doable with base64! Even then, that is horrible. I'd look for other avenues for caching files (e.g. the browser's file cache, unless that was deprecated).

Related