I want to replace the src
attribute of all <img>
elements in a certain element, that have not been loaded, because the source was not found (404).
There are quite a few topics on this here:
Most of the answers add an eventListener on the images that wait for an error
event. Ideally we'd just write something like this:
Not working example of an delegated event listener:
$("#element").on("error", "img", function(){
console.log("hey, there was an error in this image: "+$(this));
})
Another user was kind enough to point this out.
This is not working because the error
event seem not to bubble, like the click
event for example.
So with this knowlege, the only thing left seems to be, to iterate each image and check it for errors.
Whats the point (tl;dr)?
And here my question: What is the fasted method to iterate all images of a certain object for errors with javascript (yes, you may use jQuery). By fastest I mean: the iteration should be quite quick and unnecessary event listeners should not be placed (my problem).
This is my example code:
$(function(){
var $element = $("#element");
var replaceImgSrc = "http://www.placehold.it/100x100&text=replaced";
var allImages = $element.find("img");
for (var i = 0; i < allImages.length; i++) {
$(allImages[i]).one('error', function () {
$(this).attr("src", replaceImgSrc).addClass("not-loaded")
});
}
});
And here is a jsFiddleDemo: http://jsfiddle.net/qq2ccx05/ The performance in the jsFiddle is awful, it's better in production.
I'd like to know if there is a smarter way to solve this problem.