I put together an image preloader which works fine, but what doesn’t work is updating the status after every image that has been loaded. Instead, all images are loaded and “done” (last line) is the only thing that shows up. It does work when I use an alert instead of the innerHTML command, but that is obviously of no use. What am I doing wrong?
<div id="preloader">
<span id="preloader_status"> </span>
<script language="JavaScript">
imageObj = new Image();
images = new Array();
images[0]="bigimage.gif"
images[1]="anotherbigimage.gif"
/* and so on */
var i = 0;
var o = (images.length);
for (i=0;i<o;i++) {
var status = (Math.round(100*(i/o)));
imageObj.src=images[i];
document.getElementById("preloader_status").innerHTML = status;
}
document.getElementById("preloader_status").innerHTML = "done";
</script>
</div>
To show image load progress, you will need to hook into the
onloadevent for the images so you can track when their loading is actually complete. Images are loaded asychronously so assigning.srconly STARTS the loading of the image. It is not completed until later when theonloadhandler is called. Because of that, your existing code will just immediately show “done” because it isn’t tracking when the images are actually done loading.In addition, you were successively assigning a new
.srcvalue to the same image object which is going to abort the previous image loading. You need to create a new image object for each new image you are loading.You can fix your code like this: