Home > Back-end >  Switching img src to one that has already been fetched
Switching img src to one that has already been fetched

Time:06-30

I have a list of images as buttons and when clicked a modal appears that has the image on the left with text on the right. But when I switch the src of the image in the modal the browser refetches the image from the database. Is there a way to switch the image without refetching since it has already been downloaded?

$(button).on("click", function () {
  // GET ALL THE INFO NEEDED FOR THE CARD
  const imgURL    = this.querySelector("img").src;
  const name      = this.querySelector(".__name").innerHTML;
  const position  = this.querySelector(".__position").innerHTML;
  const questions = this.querySelectorAll('[data-js="question"]');
  const answers   = this.querySelectorAll('[data-js="answer"]');

  // POPULATE THE CARD
  employeeCard.querySelector(".__name").innerHTML     = name;
  employeeCard.querySelector(".__position").innerHTML = position;
  employeeCard.querySelector(".__img").src            = imgURL;

  // CONSTRUCT ANSWERS AND QUESTIONS

  // SHOW THE CARD AFTER 200 MS
  setTimeout(() => {
      $(employeeCard).toggleClass("active");
  }, 200);
});

for the fact that the browser refetches the image on change. Thanks for answers in advance.

CodePudding user response:

Convert the image and re-use it would be my though! You can implement clean-up if say they have 50 items loaded. The output of GenerateAvatar will give you a src ready input text.

    let GenerateAvatar = (url, resolve) => {
        fetch(`image_url`).then((response) => {
            return response.blob();
        }).then(blob => {
            let reader = new FileReader();
            reader.onloadend = () => resolve(reader.result);
            reader.onerror = () => resolve(null);
            reader.readAsDataURL(blob);
        });
    };

// Take the generatedAvatar/Image and re-use that someway/somehow!

CodePudding user response:

Dave's comment helped me find my problem. I had my browser disabled cache still turned on so it was constantly fetching. When I turned that off it would just use the cached image. Thank you also BGPHiJACK for your input as well.

  • Related