multiple image preloader in javascript, code needs reordering...help

768 views Asked by At

I came across a tutorial to load an image into the cache then on completion redirect to another page. I would like to do this with an array of images then when they are all loaded redirect to a new page. It mentions this in the tutorial as well but not in completion. I have tried reorganizing this code to do it but as I am a complete javascript noob I cannot combine the two and get it to work.

Here is the website http://www.techrepublic.com/article/preloading-and-the-javascript-image-object/5214317

If someone could post the code up I would be very thankful. Also I reckon a lot of people would find it useful to use it as a preloader for sites with large background images.

Cheers

UPDATE

Thanks Luke, I tried the code below, but still no joy unfortunately.....any ideas???

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

<script language = "JavaScript">

function preloader() 

{

var loadedCount = 0;
var myImagesToPreload = ["images/threewheelerback.jpg", "images/grunge.png", "images/smalllogo2.jpg"];

function loaded() {
 loadedCount++;
 if (loadedCount == myImagesToPreload) {
     location.href="history.html";
 }
}

function preloader() 
{
     for(i=0, imageObj; i<=myImagesToPreload.length; i++) 
     {
          imageObj = new Image()
          imageObj.src=myImagesToPreload[i];
          imageObj.onload = loaded;
     }
} 
}

</script>

<title>Untitled Document</title>
</head>
<body onLoad="javascript:preloader()">



<body>
Loading....
</body>
</html>

Blockquote

2

There are 2 answers

2
Luke On
var loadedCount = 0;
var myImagesToPreload = ["image1.jpg", "image2.jpg", "image3.jpg"];

function loaded() {
 loadedCount++;
 if (loadedCount == myImagesToPreload) {
    // Here you can leave the page...
 }
}

function preloader() 
{
     for(i=0, imageObj; i<=myImagesToPreload.length; i++) 
     {
          imageObj = new Image()
          imageObj.src=myImagesToPreload[i];
          imageObj.onload = loaded;
     }
} 
0
mikedeveloper On

I found one which works a treat.

Here it is if anyone wants to do the same

http://www.knowledgesutra.com/forums/topic/21316-image-preloader-with-progress-bar-status/