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

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

    Image.onload() will often work.

    To use it, you'll need to be sure to bind the event handler before you set the src attribute.

    Related Links:

    • Mozilla on Image.onload()

    Example Usage:

        window.onload = function () {
    
            var logo = document.getElementById('sologo');
    
            logo.onload = function () {
                alert ("The image has loaded!");		
            };
    
            setTimeout(function(){
                logo.src = 'https://edmullen.net/test/rc.jpg';         
            }, 5000);
        };
     
        
        Image onload()
        
        
    
        
    
        
        
        

提交回复
热议问题