Check if an image is loaded (no errors) with jQuery

前端 未结 15 1343
挽巷
挽巷 2020-11-21 20:45

I\'m using JavaScript with the jQuery library to manipulate image thumbnails contained in a unordered list. When the image is loaded it does one thing, when an error occurs

15条回答
  •  灰色年华
    2020-11-21 21:14

    This is how I got it to work cross browser using a combination of the methods above (I also needed to insert images dynamically into the dom):

    $('#domTarget').html('');
    
    var url = '/some/image/path.png';
    
    $('#domTarget img').load(function(){}).attr('src', url).error(function() {
        if ( isIE ) {
           var thisImg = this;
           setTimeout(function() {
              if ( ! thisImg.complete ) {
                 $(thisImg).attr('src', '/web/css/img/picture-broken-url.png');
              }
           },250);
        } else {
           $(this).attr('src', '/web/css/img/picture-broken-url.png');
        }
    });
    

    Note: You will need to supply a valid boolean state for the isIE variable.

提交回复
热议问题