Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 21, 2022 12:18 pm GMT

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