EDIT2: I decided to use javascript to load images. In my opinion, this is not the cleanest way to do things, but it works. Thank you!
That's the way to go. Svelte doesn't try to wrap everything JS, but only what it can add real value to. Here JS is perfectly equipped to handle this need.
You can use a Svelte action to make it more easily reusable:
<script>
let waiting = 0
const notifyLoaded = () => {
console.log('loaded!')
}
const onload = el => {
waiting++
el.addEventListener('load', () => {
waiting--
if (waiting === 0) {
notifyLoaded()
}
})
}
</script>
<img use:onload src="https://place-hold.it/320x120" alt="placeholder" />
<img use:onload src="https://place-hold.it/120x320" alt="placeholder" />
If you need to reuse this across multiple components, you might want to wrap this pattern into a factory (REPL):
util.js
export const createLoadObserver = handler => {
let waiting = 0
const onload = el => {
waiting++
el.addEventListener('load', () => {
waiting--
if (waiting === 0) {
handler()
}
})
}
return onload
}
App.svelte
<script>
import { createLoadObserver } from './util.js'
const onload = createLoadObserver(() => {
console.log('loaded!!!')
})
</script>
<img use:onload src="https://place-hold.it/320x120" alt="placeholder" />
<img use:onload src="https://place-hold.it/120x320" alt="placeholder" />
<svelte:window on:load="{()=>handleonload()}"/>more info svelte.dev/tutorial/svelte-window - dagaltion:loadfunction, unlikeonMount, is not triggered. Any way to work around this? - Haowen Liu