Useful Snippets


This blog is used to collect useful snippets related to Linux, PHP, MySQL and more. Feel free to post comments with improvements or questions!

Are your smart devices spying on you? Make better purchasing choices and find products that respect your privacy at

RSS Latest posts from my personal blog

Most viewed posts

Subscribe to RSS feed

Preloading images in Svelte

Stanislav KhromovStanislav Khromov

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 -->
  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`);

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

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

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

Web Developer at Aftonbladet (Schibsted Media Group)
Any opinions on this blog are my own and do not reflect the views of my employer.
Twitter Profile
Visit my other blog

Comments 0
There are currently no comments.