Why is Chrome is only calling the onerror event for the img element one time when all other browsers (IE7,8,9, FF, Opera, and Safari) all call it repeatedly?
Is there a way to force it to repeat the onerror call again (in Chrome)?
HTML:
<div id="thisWorks">
this works in Chrome. onerror event is called once.
<img src="http://www.asdfjklasdfasdf.com/bogus1.png"
onerror="fixit(this);"
rsrc="http://eatfrenzy.com/images/success-tick.png" />
</div>
<div id="thisDoesNotWork">
this does not work in Chrome. onerror event is not called twice.
<img src="http://www.asdfjklasdfasdf.com/bogus1.png"
onerror="fixit(this);"
rsrc="http://www.asdfjklasdfasdf.com/bogus2.png|http://eatfrenzy.com/images/success-tick.png" />
</div>
JAVASCRIPT:
function fixit(img)
{
var arrPhotos = img.getAttribute('rsrc').split('|');
// change the img src to the next available
img.setAttribute('src', arrPhotos.shift());
// now put back the image list (with one less) into the rsrc attr
img.setAttribute('rsrc', arrPhotos.join('|'));
return true;
}
EDIT:
Per @Sunil D.'s comment about Chrome not issuing a new lookup due to invalid domain name of www.asdfjklasdfasdf.com
in the initial fiddle example, I went ahead and changed the domain name to match that of the success image, but with a different filename so it still is a 404. That will prove it's not the invalid domain name causing Chrome to bail out on the 2nd attempt.
EDIT: Updated fiddle and removed use of jquery to simply things and rule that out.
Okay got it. Inside the function you assign to the onerror event, set the src
attribute to null
before changing it to it's new value.
img.setAttribute('src', null);
working fiddle
This somehow causes Chrome to reset it and will force it to repeatedly call onerror if subsequent values for src
return an error.
Note: an empty string won't work and needs to be null
.
Note2: this fix works using pure javascript (but not with the jquery .attr
method). After I posted this solution I tried it with the jquery .attr
method setting it to $img.attr('src', null);
but it didn't work that way and when I changed it to javascript, it worked. I also tried it using the jquery .prop
method instead like so $img.prop('src', null);
which worked the first time and failed on a few subsequent refreshes. Only the pure javascript seems to be a surefire solution.
UPDATE:
Okay, turns out that while the above change fixes Chrome and causes it to repeatedly call onerror like all other other browsers (FF, Safari, Opera, IE7-9), it causes problems with the onerror event for IE10 and thus ignores any valid images assigned to src
after setting it to =null
on the previous line. (...sigh).