Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

108
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda