Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

106
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!