Useful Snippets

Welcome!


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 Unwanted.cloud

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 -->
<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>

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.
LinkedIn
Twitter
WordPress.org Profile
Visit my other blog

Comments 0
There are currently no comments.