'How to prevent redownloading of image when using html()?

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?



Solution 1:[1]

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

Solution 2:[2]

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.

Solution 3:[3]

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

Solution 4:[4]

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

var img = new Image(100, 200);
img.src = 'picture.jpg';

then on your onChange function of select you can call on the img on your code it should be like this:

selectedDiv.html(img);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dvpgg
Solution 2 Ocram
Solution 3 Ziadi Lotfi
Solution 4