DEV Community

Cover image for Loading images with Svelte
Andrei Roba
Andrei Roba

Posted on

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;
    };
})
Enter fullscreen mode Exit fullscreen mode

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}
Enter fullscreen mode Exit fullscreen mode

A full working example can be found here.

Cover photo by Mike van den Bos on Unsplash

Top comments (0)