How to create a JavaScript callback for knowing when an image is loaded?

前端 未结 10 1372
太阳男子
太阳男子 2020-11-22 04:56

I want to know when an image has finished loading. Is there a way to do it with a callback?

If not, is there a way to do it at all?

10条回答
  •  甜味超标
    2020-11-22 05:45

    If you are using React.js, you could do this:

    render() {
    

    // ...

     this.onImgLoad({ item })}
    onError={() => this.onImgLoad({ item })}
    
    src={item.src} key={item.key}
    ref={item.key} />
    

    // ... }

    Where:

  • - onLoad (...) now will called with something like this: { src: "https://......png", key:"1" } you can use this as "key" to know which images is loaded correctly and which not.
  • - onError(...) it is the same but for errors.
  • - the object "item" is something like this { key:"..", src:".."} you can use to store the images' URL and key in order to use in a list of images.

提交回复
热议问题