jQuery callback on image load (even when the image is cached)

前端 未结 14 1202
轻奢々
轻奢々 2020-11-21 06:25

I want to do:

$(\"img\").bind(\'load\', function() {
  // do stuff
});

But the load event doesn\'t fire when the image is loaded from cache

相关标签:
14条回答
  • 2020-11-21 07:28

    If the src is already set, then the event is firing in the cached case, before you even get the event handler bound. To fix this, you can loop through checking and triggering the event based off .complete, like this:

    $("img").one("load", function() {
      // do stuff
    }).each(function() {
      if(this.complete) {
          $(this).load(); // For jQuery < 3.0 
          // $(this).trigger('load'); // For jQuery >= 3.0 
      }
    });
    

    Note the change from .bind() to .one() so the event handler doesn't run twice.

    0 讨论(0)
  • 2020-11-21 07:28

    A modification to GUS's example:

    $(document).ready(function() {
        var tmpImg = new Image() ;
        tmpImg.onload = function() {
            // Run onload code.
        } ;
    
    tmpImg.src = $('#img').attr('src');
    })
    

    Set the source before and after the onload.

    0 讨论(0)
提交回复
热议问题