Reputation: 63
I am trying to load images to a table dynamically without having to use server side code. It works, but I want to be able to have an infinite loop that breaks when a picture fails to load, rather than hard code the number of rows I need. That way I won't ever have to update the code, I'll just be able to add pictures to a folder if I want to expand the table.
Right now the "onerror" attribute hides the failed image, but I also want to break out of the outer loop (loop1).
function headCatalogLoader() {
var table = document.getElementById("catalog");
var meshNum = 0;
var uniqueID = 0;
loop1:
for (var i = 0; i <= 50; i++) { // i made it 50 instead of infinite for now
var row = table.insertRow(i);
loop2:
for (var k = 0; k <= 2; k++) { // 2 is because 3 columns
var skinTone = "none";
var cell = row.insertCell(k);
if (k == 0) {
skinTone = "lgt";
}
else if (k == 1) {
skinTone = "med";
}
else if (k == 2) {
skinTone = "drk";
}
cell.innerHTML = "<img src=\"headimgs/head" + skinTone + meshNum + ".png\" id=\"head" + uniqueID + skinTone + "\" onclick=\"previewIt(this)\" onerror=\"$(this).hide();\" />";
uniqueID++;
}
meshNum++;
}
var tbody = $("table tbody");
tbody.html($("tr",tbody).get().reverse());
}
Breaking from within the attribute is out of the loop's scope and doesn't work. Also using
$('img').on("error", function () {
break loop1;
});
inside loop2 doesn't do anything. Any help or suggestions would be wonderful!
Upvotes: 1
Views: 703
Reputation: 2910
This is a recursion method that you can implement for the above requirement, I have used timeout because the image load may take time if, So error could occur after loading few hundreds of images, feel free to adjust the timeout interval.
Below implementation will load 10 images per second.
var imageLoadError = false;
function loadImage() {
if (imageLoadError) {
return;
}
var img = document.createElement('img');
img.onerror = function () {
imageLoadError = true;
}
img.src = '/image/url/here'; // THE NEXT IMAGE TO LOAD
setTimeout(function () {
loadImage()
}, 100); // <= Timeout Interval
}
If performance is not critical, Here is the most recommanded way of doing it.
var imageLoadError = false;
function loadImage() {
if (imageLoadError) {
return;
}
var img = document.createElement('img');
img.onerror = function () {
imageLoadError = true;
}
img.onload = function () {
loadImage();
}
img.src = '/image/url/here'; // THE NEXT IMAGE TO LOAD
}
In this second implementation, the next image only loads after the last image is loaded. So this strategy will be slower than the first one.
In both implementation just call loadImage()
once and it will do it.
Upvotes: 2