An Interest In:
Web News this Week
- March 27, 2024
- March 26, 2024
- March 25, 2024
- March 24, 2024
- March 23, 2024
- March 22, 2024
- March 21, 2024
January 21, 2022 12:18 pm GMT
Original Link: https://dev.to/andreirobadev/loading-images-with-svelte-4a5c
Loading images with Svelte
Poor network conditions cause images to load slower, sometimes leading to broken layouts. You could exclusively rely on the alt attribute, but a more robust solution would handle such cases. Therefore, showing a placeholder or a spinner until displaying a fully loaded image could significantly improve the user experience.
The Image web API exposes two methods, onload
and onerror
that help managing these situations:
import { onMount } from 'svelte'export let src;let loaded = false;let failed = false;let loading = false;onMount(() => { const img = new Image(); img.src = src; loading = true; img.onload = () => { loading = false; loaded = true; }; img.onerror = () => { loading = false; failed = true; };})
the above Svelte code is part of an Image
component with the following template:
{#if loaded} <img {src} />{:else if failed} <img src="not_found.jpg" />{:else if loading} <img src="loading.gif" />{/if}
A full working example can be found here.
Cover photo by Mike van den Bos on Unsplash
Original Link: https://dev.to/andreirobadev/loading-images-with-svelte-4a5c
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