Caching images from a database in JS: preloading not working as expected

I’m trying to cache images in my JavaScript app so users can view them offline. I’m using a function to preload about 200 images:

function loadImageBefore(imageUrl) {
  return new Promise((resolve) => {
    const picture = new Image();
    picture.src = imageUrl;
    picture.onload = resolve;
    picture.onerror = resolve;
  });
}

But when the app tries to show the images, it ignores the preloaded ones and tries to load them again. Without internet, it fails.

I tried loading images in groups, but that didn’t help either. When I preload just one image, it works for some but not others.

The weird thing is, when I don’t preload and just view the images with good internet, they show up fine. So the image URLs aren’t the problem.

I’m getting these images from a database. Could that be causing issues? Any ideas on how to make this work? I really need the images to show up even when there’s no connection.

Your approach seems logical, but there might be a few things to consider. Have you verified that the preloaded images are actually being stored in the browser’s cache? It’s possible that the caching mechanism isn’t working as expected. Also, ensure you’re using the same exact URLs when trying to display the images later. Even minor differences can cause the browser to treat them as separate resources. Additionally, you might want to look into using the ‘fetch’ API with a custom cache strategy. This could give you more control over how the images are stored and retrieved. Lastly, double-check your database connection and ensure it’s not interfering with the caching process somehow.

hey man, sounds like a tricky issue. have u tried using the cache API instead? it’s designed for offline storage and might work better for ur use case. u could store the image blobs there after fetching. just a thought, might be worth lookin into. good luck!

I’ve dealt with similar caching issues before and found that using IndexedDB rather than relying solely on the browser cache can make a significant difference. Although the setup is a bit more complex, it gives you much better control over storing and retrieving large amounts of data like images. In my experience, I first fetched images and stored them as Blobs in IndexedDB. When displaying images, I checked the database first and only fell back to a network request when necessary. This approach improved offline access considerably. Be mindful of quota errors since browsers impose storage limits, and consider implementing a cleanup strategy to remove old or unused images.