Sir
Sir

Reputation: 8280

image onload not working in javascript

I have an array of 2 images but the onload does not fire for the second image. But in chrome resources the image is there all nice and loaded... what could cause this ?

This is my code:

var test = new Array();
    test[0] = new Image();
    test[0].src = 'tile1.png';  
    test[1]  = new Image();
    test[1].src = 'tile2.png';      


    test[0].onload = function(){    
        console.log('loaded 1');    

            test[1].onload = function(){
               console.log('loaded 2');
        }
    }

I only get loaded 1 in my console.log but never loaded 2.

Yet in Chrome network it shows tile2.png so why would my onload function not fire??

Upvotes: 1

Views: 7224

Answers (1)

Joseph Myers
Joseph Myers

Reputation: 6552

Your second onload function is declared within the first, so remove it and place it outside.

var test = new Array();
test[0] = new Image();
test[0].src = 'tile1.png';  
test[1]  = new Image();
test[1].src = 'tile2.png';      


test[0].onload = function(){    
    console.log('loaded 1'); 
}

test[1].onload = function(){
    console.log('loaded 2');
}

Upvotes: 3

Related Questions