Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

107
Vistas
Fall back image with SvelteKit

I got started with Svelte(Kit) and I really like it so far. However, I ran into an issue that I couldn't resolve.

I'm trying to dynamically display images and like to have a fall back image in case the normal one does not exist.

With vanilla HTML/JS, I would use this Source:

<img src="imagefound.gif" onerror="this.onerror=null;this.src='imagenotfound.gif';" />

I tried to make it happen in my Svelte project, but it either does not work (e.g. A) or it works sometimes (for a brief moment or until I refresh (e.g. B)).

This is my code (A):

<script>
let profileImg = person.profile;
const missingProfile = () => {
    console.log('image does not exist');
    profileImg = '../default.png';
};
</script>

...

<img
    src={profileImg}
    on:error={missingProfile}
    alt={person.name}
/>

or just the hardcoded version (B)

<img 
    src="imagefound.gif" 
    onerror="console.log('image not found');this.onerror=null;this.src='./person.png';" 
/>

There is this question, but I believe the answer is what I am doing. Is there a difference whether I use SvelteKit vs. Svelte?

Addition

It looks like that Svelte does not even set the src for the <img />, if the original variable with the url for the image is undefined (in my example person.profile). The accepted answer wouldn't work in that case.

I edited this line to prevent that case:

let profileImg = person.profile === undefined ? '../default.png' : person.profile;
about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

This code works in SvelteKit

<script>
    let fallback = 'http://placekitten.com/200/200'
    let image = ""
    
    const handleError = ev => ev.target.src = fallback
</script>

<img src={image} alt="" on:error={handleError}>
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda