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

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

    Not suitable for 2008 when the question was asked, but these days this works well for me:

    async function newImageSrc(src) {
      // Get a reference to the image in whatever way suits.
      let image = document.getElementById('image-id');
    
      // Update the source.
      img.src = src;
    
      // Wait for it to load.
      await new Promise((resolve) => { image.onload = resolve; });
    
      // Done!
      console.log('image loaded! do something...');
    }
    

提交回复
热议问题