Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 23, 2021 10:41 pm GMT

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.

Example:

<!-- Slider.svelte --><script>    const numberOfImages = 5;    // This will generate an array of urls such as /images/1.jpg, /images/2.jpg, 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.


Original Link: https://dev.to/khromov/preloading-images-in-svelte-465h

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To