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

前端 未结 10 1107
太阳男子
太阳男子 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:38

    Life is too short for jquery.

    function waitForImageToLoad(imageElement){
      return new Promise(resolve=>{imageElement.onload = resolve})
    }
    
    var myImage = document.getElementById('myImage');
    var newImageSrc = "https://pmchollywoodlife.files.wordpress.com/2011/12/justin-bieber-bio-photo1.jpg?w=620"
    
    myImage.src = newImageSrc;
    waitForImageToLoad(myImage).then(()=>{
      // Image have loaded.
      console.log('Loaded lol')
    });

提交回复
热议问题