Image Preloader MKII

Image preloader MKII makes sure that all your images have downloaded before they are used.




Over 2000+ free Javascript
at JavaScriptBank.com Website

Sampled by JavaScriptBank.com
The thumbnail display is only a visual reference for this example to show the images being preloaded.


A common mistake when preloading images is to simply create an Image object and assign a Source, but if the image is used before it has loaded, this preloading will have no effect at all. To make preloading work properly, the images have to complete loading before they are used.

Typical examples of this would be where images are shown at random or a slideshow script.

The Image Preloader MKII ensures that all images are downloaded before they can be displayed.

A couple of additional features are the ability to see how many images remain to be downloaded and the inclusion of a progress bar to let your visitor know that something is happening.

The preloader works by creating a new image object that is assigned an onload event so that when the current image has preloaded a function is run to check for the next image in the array.

Once all the images are preloaded your function is run.

If you want to preload in the background without the counter or progress bar comment out the appropriate lines

<script language="javascript">
<!--
// Realised by ApacheJeff
// www.huntingground.freeserve.co.uk

images=new Array("pic01.jpg","pic02.jpg","pic03.jpg","pic04.jpg","pic05.jpg")

img_total=images.length // counter display

a_index=0
var preloaded=new Array()

function load_image(){
preloaded[a_index]=new Image()
preloaded[a_index].onload=check_array
preloaded[a_index].src=images[a_index]
}

function check_array(){
a_index++

document.getElementById("info").innerHTML="Loading "+img_total // counter display
img_total-- // counter display
progress() // progress bar function

if(a_index!=images.length){
setTimeout("load_image()",10)
}
else{
do_this() // function to run

document.getElementById("info").innerHTML="" // counter display
document.getElementById("progress_bar").style.visibility="hidden" // progress bar display
document.getElementById("bg_layer").style.visibility="hidden" // progress bar display

}

}

// progress bar display
Width=300 // width of bar
step_size=Width / images.length // calculates step size
step=0
function progress(){
step+=(step_size*1)
document.getElementById("progress_bar").style.width=step
}

function do_this(){
alert("All the images have now been downloaded")
}

// add onload="load_image()" to the opening BODY tag

//-->
</script>

<!--display count-->
<div id="info"></div>

<!-- progress bar display-->
<div id="bg_layer" style="position:absolute;left:180;top:100;width:300;background-color:#8e8462;font-size:10">&nbsp;</div>
<div id="progress_bar" style="position:absolute;left:180;top:100;width:0;background-color:#c9bda9;z-index:2;font-size:10">&nbsp;</div>