By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
464,367 Members | 1,270 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 464,367 IT Pros & Developers. It's quick & easy.

Problem Pre-Loading Images Using Javascript

P: 1
I am trying to get the following code to pre-load some images before re-dirrecting the user. The problem is that the onError event gets called for all of the images immediately. I've tripple checked that the images do in fact exist at the specific url, so I can't figure out why the onError is being called. The script is currently posted on http://www.mkcustomdesign.com/index.html.


<script type="text/javascript">

var imagesToLoad = 0;
var imagesLoaded = 0;

function loadImages(){


images = new Array("loading.jpg", "row1.jpg", "index_02.jpg", "index_03.jpg", "index_03.jpg", "index_04.jpg", "index_05.jpg",
"index_06.jpg", "mkcustom.jpg", "spacerrow.jpg", "box_1_1_table.jpg", "box_1_2_chair.jpg",
"box_1_3_bed.jpg","side_1_right.jpg", "side_1_left.jpg", "row3.jpg", "side_2_left.jpg",
"box_2_1_cabinets.jpg" , "box_2_2_railing.jpg", "box_2_3_misc.jpg", "side_2_right.jpg",
"bottom2.jpg" );

imagesToLoad = images.length;
for(i = 0; i < images.length; i++){
image = new Image();
image.onLoad = imageLoaded();
image.onError = error("images/" + images[i]);
image.src = "images/" + images[i];
}

}

function error(image){
alert('error with ' + image);
}

function imageLoaded(){
imagesLoaded++;
document.getElementById('loading').innerHTML = 'Loaded ' + imagesLoaded + "/" + imagesToLoad + ' images ';
if(imagesLoaded == imagesToLoad){
//document.location = "main.html";
}
}


</script>
Apr 25 '07 #1
Share this Question
Share on Google+
1 Reply

100+
P: 210
Expand|Select|Wrap|Line Numbers
  1. image.onLoad = imageLoaded();
  2.         image.onError = error("images/" + images[i]);
An event handler is passed as a function address not a function call. I haven't tested this but try it:
Expand|Select|Wrap|Line Numbers
  1. image.onLoad = imageLoaded;
  2. image.onerror = new Function("error('images/' + images[i])") ;
  3.  
As for the loaded images indicator, you may not always get onload events when testing locally.
Apr 26 '07 #2

Post your reply

Sign in to post your reply or Sign up for a free account.