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

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

    You can use the .complete property of the Javascript image class.

    I have an application where I store a number of Image objects in an array, that will be dynamically added to the screen, and as they're loading I write updates to another div on the page. Here's a code snippet:

    var gAllImages = [];
    
    function makeThumbDivs(thumbnailsBegin, thumbnailsEnd)
    {
        gAllImages = [];
    
        for (var i = thumbnailsBegin; i < thumbnailsEnd; i++) 
        {
            var theImage = new Image();
            theImage.src = "thumbs/" + getFilename(globals.gAllPageGUIDs[i]);
            gAllImages.push(theImage);
    
            setTimeout('checkForAllImagesLoaded()', 5);
            window.status="Creating thumbnail "+(i+1)+" of " + thumbnailsEnd;
    
            // make a new div containing that image
            makeASingleThumbDiv(globals.gAllPageGUIDs[i]);
        }
    }
    
    function checkForAllImagesLoaded()
    {
        for (var i = 0; i < gAllImages.length; i++) {
            if (!gAllImages[i].complete) {
                var percentage = i * 100.0 / (gAllImages.length);
                percentage = percentage.toFixed(0).toString() + ' %';
    
                userMessagesController.setMessage("loading... " + percentage);
                setTimeout('checkForAllImagesLoaded()', 20);
                return;
            }
        }
    
        userMessagesController.setMessage(globals.defaultTitle);
    }
    

提交回复
热议问题