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?
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;
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}>