1

How to build <img> load event with automatic image reloading in case of error?

Image is created by way:

 var Img = $(document.createElement('img'));
 Img.on('load',function(){
  // Some code, this handler must be saved
 });
 Img.attr('src',path);
 Img.appendTo(...

Where it used: http://vseslava.ru, big circle on index.

Rustam
  • 1,875
  • 2
  • 16
  • 33
  • 1
    http://stackoverflow.com/questions/92720/jquery-javascript-to-replace-broken-images – box86rowh Nov 11 '12 at 12:57
  • What have you tried? Is this an image put on the page via the main markup, or dynamically later? What kind of "error" are you trying to handle? 404? Something else? – T.J. Crowder Nov 11 '12 at 12:59
  • Not 404 error. Error occurring in case of internet problems with big time of image loading. – Rustam Nov 11 '12 at 13:14
  • @box86rowh This is html way without attached events. Add here that previously on image node binded load event related to some counter variable (you need to save this handler). And image created by way document.createElement, not html – Rustam Nov 11 '12 at 13:27

1 Answers1

1

you can use from this code:

$('#image1')
    .load(function(){
        $('#result1').text('Image is loaded!'); 
    })
    .error(function(){
        $('#result1').text('Image is not loaded!');
            // in this case you must reload image with jQuery
    });

this is simple,because you has image url and you can reload that and replace that in image.

Update

$("img").load(function(){
        $('#result1').text('Image is loaded!\n');
    })
    .error(function(){
        $('#result1').text('Image is not loaded!\n');
        // in this case you must reload image with jQuery
        var imgSrc = $(this).attr('src');
        $(this).attr('src',imgSrc);
});

Try Demo

user197508
  • 1,282
  • 2
  • 18
  • 31
  • There's all sorts of context missing from this answer, unlikely to be of any use to anyone in its current form. – T.J. Crowder Nov 11 '12 at 13:00
  • ...and your demo has a major race condition in it. (The `load` and `error` events may fire before you hook them.) – T.J. Crowder Nov 11 '12 at 13:06
  • I know this. I asked about automatic reloading for the same node. – Rustam Nov 11 '12 at 13:18
  • http://vseslava.ru/ Goal - this index page circle. All created on fly with javascript. Initially (in HTML) image nodes are not created. There are SVG images, but logic is same – Rustam Nov 11 '12 at 13:21
  • this is ambiguity,you want load image initially with jQuery Or load with jQuery IF image not loaded? – user197508 Nov 11 '12 at 13:27
  • I need initially to load image, but in case of error - reload it again, until it will be loaded. – Rustam Nov 11 '12 at 13:28