DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Stanislav Khromov
Stanislav Khromov

Posted on • Updated on • Originally published at snippets.khromov.se

Preloading images in Svelte

Let's say you are building a dynamic image slider and would like to preload images that aren't shown yet in the background. Svelte and the link tags preload functionality makes this a breeze.

First we generate a list of URLs - this will depend on your implementation. Second we insert <link rel="preload"... tags into the head using <svelte:head>. This will cause the browser to preload the images as soon as the page loads, even if they are not actually present in the DOM yet!

Let's look at a practical example:

<!-- Slider.svelte -->
<script>
    const numberOfImages = 5;

    // This will generate an array of urls such as /images/1.png, /images/2.png, up to numberOfImages
    $: preloadImageUrls = [...Array(maxImages).keys()].map((key) => `/images/${key+1}.png`);
</script>

<svelte:head>
    {#each preloadImageUrls as image}
      <link rel="preload" as="image" href={image} />
    {/each}
</svelte:head>

<div>
    <!-- For illustrative purposes, we will only show one image here -->
    <img src="/images/1.png" />
</div>
Enter fullscreen mode Exit fullscreen mode

We can quickly validate that the functionality works as expected using the browser dev tools.

Top comments (0)

We're hiring!

We're Hiring

We're looking for a Senior Full Stack Engineer to join the DEV team.

Head here to learn more.