Haowen Liu
Haowen Liu

Reputation: 167

Svelte component onLoad

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!

Upvotes: 12

Views: 27590

Answers (1)

rixo
rixo

Reputation: 25001

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

Upvotes: 17

Related Questions