0

I've been working on a project which has lots of images to display. I found that loading all the images costs lots of time. One friend suggested me to use cache to save the time. So I converted the images into String of Base64 and when I login the website, I stored all the necessary images to the cache and load it. But I'm not sure whether it's good practice or not. Below is the code for converting and storing images.

Hope to hear the opinions from the seniors.

THis is the code I tried.

export const imageUrlToBase64 = async (file, fileType, callback) => {

    console.log(file);
    if(file instanceof Blob) {
        imageFileToBase64(file, fileType, function(base64String) {
            if(base64String) {
                callback(base64String);
            }
        });
    } else {
        urlToBase64(file, fileType, function(base64String) {
            if(base64String) {
                callback(base64String);
            }
        });
    }
    // Create a new Image element
    
}

export const saveToCache = async (url, data) => {
  if (url === 'user') console.log(data);

  try {
    const cache = await caches.open('mychache');
    await cache.put(url, new Response(data));
  } catch (error) {
    console.error('Error saving data to cache:', error);
  }
};


export const readFromCache = async (url) => {
  
  let data = "";
  
  try {
    const cache = await caches.open('mychache');
    const response = await cache.match(url);
    if (response) {
      data = await response.text();
    }
  } catch (error) {
    console.error('Error reading from cache:', error);
  }
  if(url === 'user') console.log(data)
  return data;
};

1

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.