How to use jQuery live() for img onload event?

后端 未结 3 351
逝去的感伤
逝去的感伤 2021-01-08 00:06

I want to run some code when an image is loaded. Also, I\'d like to do it unobtrusively (not inline). More specifically, I want to use jQuery\'s live() function

相关标签:
3条回答
  • 2021-01-08 00:20

    Finaly I stumbled upon this jQuery plugin : https://github.com/desandro/imagesloaded

    0 讨论(0)
  • 2021-01-08 00:21

    (It would be load, not onload or onLoad.)

    load doesn't bubble (according to the img entry in the HTML5 spec, it's a "simple event", which don't bubble), so you can't use it with live or delegate, which rely on the event bubbling from an element to its ancestor element(s).

    You'll have to hook it on the individual img elements (and do so before you set their src, since otherwise you can miss it; and always remember to watch for error as well). (Yes, you really can miss it: The browser is not single-threaded, just the JavaScript main thread. If you set src and the image is in cache or becomes available soon enough, the browser can fire the event. The way events are fired is that the browser looks to see what handlers are registered as of when the event is fired, and queues those to be called when the JavaScript main thread yields back to the browser. If there are no handlers registered, they aren't queued, and you never get the callback.)

    0 讨论(0)
  • 2021-01-08 00:28

    it's a little bit dirty, but it works :

    <script type="text/javascript">
        var loop = setInterval(function() {
    
               // the img to watch
               var $img = $("img.hi");
    
               if( !!$img.length && $img[0].complete ) {
                   // clear the timer
                   clearInterval(loop);
    
                   alert("loaded !");
    
               }
    
        }, 30);        
    </script>
    
    <img class="hi" src="http://www.google.fr/images/nav_logo72.png" />
    
    0 讨论(0)
提交回复
热议问题