I'm trying to control the background if it available or not. I see onerror using everywhere, but not for me. I have bg folder and background1.jpg to background4.jpg background pictures. For first 4 there is no problem. But background5.jpg not available in that folder. Onerror doesn't work. How can i do about that problem? Any ideas?
<script>
var background = document.createElement("img");
var positive=1;
var x=0;
for(var i=0; i<6; i++)
{
background.src = "bg/background"+i+".jpg"
background.onerror = "finisher()"
background.onload = function(){alert("Worked!");}
function finisher()
{
positive = 0;
}
if(positive = 1)
{
alert("Vuhhuu! ->"+x);
x++;
}
else
{
alert("Image not loaded!");
}
}
</script>
There are a bunch of things wrong with your code. First off, you can use a
for
loop like this and expect it to try each image:That just won't do what you're trying to do. That will rapidly set each successive
.src
value without letting any of them actually load (asynchronously) to see if they succeed.Second off, don't use a string for
.onerror
. Assign the function reference directly such asbackground.onerror = finisher;
Thirdly, you MUST assign onerror and onload handlers BEFORE you assign
.src
. Some browsers (IE raise your hand) will load the image immediately if your image is in the browser cache and if your onload handler is NOT already installed, you will simply miss that event.If you're really trying to try each image and know which ones work, you will have to completely redesign the algorithm. The simple way would be to create 6 images, load all of them and then when the last one finishes, you can see which ones had an error and which ones loaded properly.
If you're just trying to find the first one that succeeds, then you can pursue a different approach. Please describe what you're actually trying to accomplish.
To see how many of the images load successfully, you can do this:
Note, this is an asynchronous process because images load in the background. You won't know how many images loaded or which images loaded until the callback is called sometime later when all the images have finished.