An Interest In:
Web News this Week
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
- April 20, 2024
- April 19, 2024
- April 18, 2024
December 23, 2021 10:41 pm GMT
Original Link: https://dev.to/khromov/preloading-images-in-svelte-465h
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:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To