Kokodoko
Kokodoko

Reputation: 28128

Error preloading images in IE8

I am using this code to preload image and reference them later by id. It's working in most browsers and on ipad, but IE8 generates this error:

'Unable to get property 'target' of undefined null reference'

This is my code:

var images = [{id:"kids", url:"assets/driekids.png"}, {id:"title",url:"assets/gametitle.png"}];
var assets = [];
var fnCallback = fn;
var loaded = 0;

this.startLoading = function() {
    var t = this;
    for(var i = 0;i<images.length;i++){
        var r = new Image();
        r.src = images[i].url;
        r.name = images[i].id;
        r.onload = function(){t.checkLoaded();};
    }
}

this.checkLoaded = function(e) {    
    this.assets[e.target.name] = e.target;  
    loaded++;
    if(loaded == images.length) fnCallback();       
}

My question: is this way of image preloading, by using new Image(), possible on IE8?

Upvotes: 0

Views: 356

Answers (1)

Ibu
Ibu

Reputation: 43810

In IE you get the event object like this:

window.event

so you will have to make modifications to your code:

this.startLoading = function() {
    var t = this;
    for(var i = 0;i<images.length;i++){
        var r = new Image();
        r.src = images[i].url;
        r.name = images[i].id;
        r.onload = t.checkLoaded; // you dont want an anonymous function here
    }
}

this.checkLoaded = function(e) {
    // get the event object for both IE and other browsers
    var event = e || window.event;
    var target = e.target || event.srcElement ;
    this.assets[target.name] = target;  
    loaded++;
    if(loaded == images.length) fnCallback();       
}

Upvotes: 1

Related Questions