I am trying to create a webpage where you get a random image when you open the page. I want svelte to decide on a random image when the page loads and then load that image in the “src” tag. I have a set number of images that I will choose from.
I can do this, however, I don’t want the page to get ALL of the images and then randomly select one. I would like to just randomly select one, then load that image in order to keep requests and data to a minimum.
Here is what I have now:
<script>
import heroOne from "$lib/hero.webp";
import heroTwo from "$lib/heroTwo.webp";
let heroImg;
const rand = Math.floor(Math.random() * 2);
switch(rand){
case 0: heroImg = heroOne; break;
case 1: heroImg = heroTwo; break;
}
</script>
<img src={heroImg} alt="Some alt text">
As far as I know, this is still going to load both hero images. Is there some way to only load the image once selected?