Is there a way to know when a Svelte component has finished loading all its external resources, rather than onMount
?
It is similar to the onload
event of window
.
EDIT: To clear things up, I would like a component to do something after it fully loads all its images.
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!
Is there a way to know when a Svelte component has finished loading all its external resources, rather than onMount
?
It is similar to the onload
event of window
.
EDIT: To clear things up, I would like a component to do something after it fully loads all its images.
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!
Share Improve this question edited Nov 24, 2020 at 17:45 Haowen Liu asked Nov 22, 2020 at 21:42 Haowen LiuHaowen Liu 1671 gold badge1 silver badge10 bronze badges 4 |1 Answer
Reset to default 17EDIT2: 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 – dagalti Commented Nov 23, 2020 at 15:24on:load
function, unlikeonMount
, is not triggered. Any way to work around this? – Haowen Liu Commented Nov 24, 2020 at 16:15