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

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

    If the goal is to style the img after browser has rendered image, you should:

    const img = new Image();
    img.src = 'path/to/img.jpg';
    
    img.decode().then(() => {
    /* set styles */
    /* add img to DOM */ 
    });
    

    because the browser first loads the compressed version of image, then decodes it, finally paints it. since there is no event for paint you should run your logic after browser has decoded the img tag.

提交回复
热议问题