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

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

    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.

0 讨论(0)
  • 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);
        };
     <html>
        <head>
        <title>Image onload()</title>
        </head>
        <body>
    
        <img src="#" alt="This image is going to load" id="sologo"/>
    
        <script type="text/javascript">
    
        </script>
        </body>
        </html>

    0 讨论(0)
  • 2020-11-22 05:52

    Here is jQuery equivalent:

    var $img = $('img');
    
    if ($img.length > 0 && !$img.get(0).complete) {
       $img.on('load', triggerAction);
    }
    
    function triggerAction() {
       alert('img has been loaded');
    }
    
    0 讨论(0)
  • 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...');
    }
    
    0 讨论(0)
  • 提交回复
    热议问题