How to create a JavaScript callback for knowing wh

2018-12-31 14:17发布

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?

8条回答
残风、尘缘若梦
2楼-- · 2018-12-31 14:50

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:

Example Usage:

<html>
<head>
<title>Image onload()</title>
</head>
<body>

<img src="#" alt="This image is going to load" id="sologo"/>

<script type="text/javascript">
window.onload = function () {

    var logo = document.getElementById('sologo');

    logo.onload = function () {
        alert ("The image has loaded!");        
    };

    setTimeout(function(){
        logo.src = 'http://stackoverflow.com/Content/Img/stackoverflow-logo-250.png';         
    }, 5000);
};
</script>
</body>
</html>
查看更多
十年一品温如言
3楼-- · 2018-12-31 14:52

You could use the load()-event in jQuery but it won't always fire if the image is loaded from the browser cache. This plugin https://github.com/peol/jquery.imgloaded/raw/master/ahpi.imgload.js can be used to remedy that problem.

查看更多
妖精总统
4楼-- · 2018-12-31 14:52

If you are using React.js, you could do this:

render() {

// ...

<img 
onLoad={() => this.onImgLoad({ item })}
onError={() => this.onImgLoad({ item })}

src={item.src} key={item.key}
ref={item.key} />

// ... }

Where:

  • - onLoad (...) now will called with something like this: { src: "https://......png", key:"1" } you can use this as "key" to know which images is loaded correctly and which not.
  • - onError(...) it is the same but for errors.
  • - the object "item" is something like this { key:"..", src:".."} you can use to store the images' URL and key in order to use in a list of images.

  • 查看更多
    裙下三千臣
    5楼-- · 2018-12-31 14:59

    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')
    });
    <img id="myImage" src="">

    查看更多
    不再属于我。
    6楼-- · 2018-12-31 15:00

    .complete + callback

    This is a standards compliant method without extra dependencies, and waits no longer than necessary:

    var img = document.querySelector('img')
    
    function loaded() {
      alert('loaded')
    }
    
    if (img.complete) {
      loaded()
    } else {
      img.addEventListener('load', loaded)
      img.addEventListener('error', function() {
          alert('error')
      })
    }
    

    Source: http://www.html5rocks.com/en/tutorials/es6/promises/

    查看更多
    梦该遗忘
    7楼-- · 2018-12-31 15:04

    these functions will solve the problem, you need to implement the DrawThumbnails function and have a global variable to store the images. I love to get this to work with a class object that has the ThumbnailImageArray as a member variable, but am struggling!

    called as in addThumbnailImages(10);

    var ThumbnailImageArray = [];
    
    function addThumbnailImages(MaxNumberOfImages)
    {
        var imgs = [];
    
        for (var i=1; i<MaxNumberOfImages; i++)
        {
            imgs.push(i+".jpeg");
        }
    
        preloadimages(imgs).done(function (images){
                var c=0;
    
                for(var i=0; i<images.length; i++)
                {
                    if(images[i].width >0) 
                    {
                        if(c != i)
                            images[c] = images[i];
                        c++;
                    }
                }
    
                images.length = c;
    
                DrawThumbnails();
            });
    }
    
    
    
    function preloadimages(arr)
    {
        var loadedimages=0
        var postaction=function(){}
        var arr=(typeof arr!="object")? [arr] : arr
    
        function imageloadpost()
        {
            loadedimages++;
            if (loadedimages==arr.length)
            {
                postaction(ThumbnailImageArray); //call postaction and pass in newimages array as parameter
            }
        };
    
        for (var i=0; i<arr.length; i++)
        {
            ThumbnailImageArray[i]=new Image();
            ThumbnailImageArray[i].src=arr[i];
            ThumbnailImageArray[i].onload=function(){ imageloadpost();};
            ThumbnailImageArray[i].onerror=function(){ imageloadpost();};
        }
        //return blank object with done() method    
        //remember user defined callback functions to be called when images load
        return  { done:function(f){ postaction=f || postaction } };
    }
    
    查看更多
    登录 后发表回答