2

I have this function in JS that preloads images:

// http://stackoverflow.com/questions/3646036/javascript-preloading-images
var preloaded_images = [];
function preload() {
    for (i = 0; i < arguments.length; i++) {
        preloaded_images[i] = new Image();
        preloaded_images[i].src = preload.arguments[i];
    }
}

However, some images I try to preload throw 404 errors. How can I detect a 404 within this function, without trying to add the image to the DOM?

bevanb
  • 8,201
  • 10
  • 53
  • 90

1 Answers1

2

You could attach the onerror eventHandler:

...
preloaded_images[i].onerror = function() {
    // the image couldn't be loaded..
}
...

And if you want to know it was loaded successful, you would do:

...
preloaded_images[i].onload = function() {
    // the image was loaded successful..
}
... 

Fiddle

putvande
  • 15,068
  • 3
  • 34
  • 50