Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
2
rated 0 times [  4] [ 2]  / answers: 1 / hits: 13179  / 4 Years ago, sun, november 22, 2020, 12:00:00

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!


More From » svelte

 Answers
3

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" />

[#2259] Tuesday, November 17, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gavenmekhio

Total Points: 732
Total Questions: 89
Total Answers: 93

Location: Central African Republic
Member since Mon, Aug 10, 2020
4 Years ago
gavenmekhio questions
Mon, Jun 21, 21, 00:00, 3 Years ago
Mon, Nov 23, 20, 00:00, 4 Years ago
Wed, Jul 29, 20, 00:00, 4 Years ago
Mon, Feb 17, 20, 00:00, 4 Years ago
;