I am trying to pre-load many (thousands) of images, and thought I was doing it right. I have all the URLs (some are valid, some are not) in an array. I loop through the array, and attache onload
and onerror
events to the img.src
function. When the image event returns an error
I do not add it to the "good" array, and I continue
in my loop.
However, I have noticed that, while this should prevent images from making it into my "good" array, it does not always (Actually I have enough images that I can't tell if it ever does). When I actually go to load those images into the page, I get the broken image symbol and a 404
in my console.
I see 404
errors in my console while pre-loading, so I am assuming it does detect some broken images but not all, or maybe they still make it into my other array? Could it be that the images are being loaded so fast that the continue
statement I have does not work (There are thousands)? If so, is there a way around this? I have attached my code below, here I tried using continue
in the .onerror
condition but I guess the img.src
made it an invalid loop condition. Thank you for any help.
EDIT:
The src
attribute is one property of an object, it also will have name
and userName
properties, so I only want to add the objects with valid urls. I tried to abbreviate my code but should have added this part (I only added the first three lines, even though I now realize I should push
the item onload
var name = 'test',
username = 'testUser'
url;
for(i = 0; i < imgURLs.length; i++) {
url = url[i];
var img = new Image();
valid = true;
img.onload = function(){
console.log('New Media Loaded')
};
img.onerror = function(){
console.log('error: bad image source');
valid = false;
};
img.src = url;
if(valid) {
goodArray.push(img);
}
}