Search code examples
javascriptsveltesveltekit

How can I conditionally load images in Svelte?


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?


Solution

  • As far as I know, this is still going to load both hero images.

    Not necessarily.

    The imports turn into URLs, the resources that the URLs point to are only loaded if they are used somewhere, in this case an image src.

    If this is a SvelteKit page with SSR, it might load both due to discrepancies between SSR & hydration, i.e. the server randomizes a different image than the client. You could use a server load function to determine a stable random index. Alternatively a seeded RNG could be used.