Page 1 of 1

javascript preloader

Posted: Wed Oct 08, 2008 10:11 am
by iris
i ve a table that contains images in its tds. i'd like to run a preloader image pending the time the images in the tds load, but when ever i run the preloadimages() onload event of the body tag the preloaders are loaded and are not repalced wen the real images are loaded. im sure its a bug on my script pls help me resolve it.

Again i'd would like to understand the concept behind the javascript image object, when does the image begin to load? is it when the object src is set to the image path or when ?

function initialiseImgs(){
var imgs = document.getElementById('content').getElementsByTagName('img')
return imgs
}


function preloadImages(){
var imgs = initialiseImgs();
var count = imgs.length
var imageSrc=''
var virtualImg = new Image()
for(i=0; i<count; i++){
imageSrc = imgs.src
virtualImg.onload = function(){imgs.src=imageSrc;}
imgs.src = 'loader.gif'
virtualImg.src = imageSrc
}
}

Re: javascript preloader

Posted: Fri Oct 10, 2008 4:12 pm
by kpowell
Give this a try

Code: Select all

function preloadImages(){
    var imgs = document.getElementById('content').getElementsByTagName('img');
    var count = imgs.length;
    var imageSrc = [];
    var virtualImg = [];
    for (i = 0; i < count; i++) {
        virtualImg[i] = new Image();
        imageSrc[i] = imgs[i].src;
        virtualImg[i].onload = function() {
            for(var j = 0, jl = virtualImg.length; j < jl; j++) {
                if(this.src == virtualImg[j].src) break;
            }
            imgs[j].src = imageSrc[j];
        }
        imgs[i].src = 'loader.gif';
        virtualImg[i].src = imageSrc[i];
    }
}
In your current code, it's trying to use "i" as it is when the image has finished loading. I don't think this is the best solution, but, for the life of me, I can't think of a better one right now.

Re: javascript preloader

Posted: Fri Oct 10, 2008 4:35 pm
by VladSun
I suppose that you want to preload images BEFORE the body contents. That's why images are preloaded in the HEAD part. But in the HEAD part you don't have any access to the BODY elements because it's not loaded yet ;)
So, calling preloading images on BODY ONLOAD event doesn't make any sense :)

You need to manually create (in HEAD) a list of images to preload and preload them (in HEAD) by explicitly calling the preloader function in HEAD.