0

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.

Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
  • are you sure it's actually hitting the server? Typically you'd see the network request, but the browser will just say "cached" and not actually refetch. If that's not happening, most likely the server is setting some sort of no-cache header, in which case (if you can't fix that), you can either live with it, or (potentially) [convert each image to a data uri](https://stackoverflow.com/questions/934012/get-image-data-url-in-javascript) before you change it's source, save a a `map[url]dataUri` (e.g. `imgs = {}; imgs[src] = dataUri`, and then when you switch, check if it already exists – dave Jun 29 '22 at 21:52
  • Your comment was great. It was hitting the server, but only because I still had disable cache turned on. Thank you for your help! – Wade Honeycutt Jun 29 '22 at 21:59

2 Answers2

0

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!
BGPHiJACK
  • 1,277
  • 1
  • 8
  • 16
0

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.