views:

46

answers:

2

I have a Javascript Map kit, and it use Image object to load images. Every time I move/resize the map, it will load many images. But I want to know how I can fire a function when all images are loaded after I do a move/resize action.

Is there a way that I can create a listener like "allimages.onload=function(){}" ?

Or is there any workaround?

+1  A: 

You would have to maintain a count of how many images were yet to load, and call the final function when the outstanding image count reached 0. eg.

function nofunction() {}

function loadImages(srcs, callback) {
    var images= [];
    var imagen= srcs.length;
    for (var i= 0; i<srcs.length; i++) {
        var image= new Image();
        image.onload=image.onerror= function() {
            imagen--;
            if (imagen==0) {
                this.onload=this.onerror= nofunction;
                callback();
            }
        };
        image.src= srcs[i];
        images.push(image);
    }
    return images;
}

...

var images= loadImages(['/img/1.gif', '/img/2.gif'], function() {
    alert('yay');
});

for (var i= 0; i<images.length; i++)
    mapelement.appendChild(images[i]);
bobince
Thank you. Maybe this is what I want and I will give it a try soon
Mickey Shine
A: 

A while ago I have written a blog post about detecting the load of a single image. You can use the example to build your function that checks if all images are loaded. I hope it will help.

Elzo Valugi