Home > database >  How to prevent redownloading of image when using html()?
How to prevent redownloading of image when using html()?

Time:04-11

I have a dropdown which replaces the image based on the selected value:

let selectedDiv = $('#selected_div');
let imageSource = $(this).find('img').attr('src');
selectedDiv.html("<img src='"   imageSource   "'>");

But then every time I choose a dropdown item, I can see in the network tab that it reloads the image. How can I download the necessary images of the dropdown once and reuse them?

CodePudding user response:

One solution would be to add every image in your div, with display:none, and make a small JS function triggered on change of your dropdown that will change the display of the image related to your dropdown value to block, and set the display values of the other images to none to be sure to not display more than one image.

That way, your images will be loaded once, but they will be hidden, except you select the right dropdown value

CodePudding user response:

Are you sure that your browser downloads image again? Image will be showed in your network tab even if it is cached on your computer. You can see that in "size" column on network tab. It will probably say "memory cache" or "disk cache".

However if you don't want to reload image, best option would be manipulating with display: none, as already mentioned.

CodePudding user response:

To avoid multiple http request use display:none and use js function to set the selected dropdown image display to block

CodePudding user response:

One way is by preloading the images using JavaScript Image()

  • Related