Skip to content

prototypes in javascript for image onload handlers

All this was trying to get it so all subsequent images created in a document would have a onload handler already setup (yes you guessed it I was trying to spy on a metrics library).

This works:
var t = new Image();
t.onload = function(){alert('yes')};
t.src="http://www.cisco.com/web/fw/i/logo.gif";

does not work
Image.prototype.onload = function(){alert('yes')};
var t = new Image();
t.src="http://www.cisco.com/web/fw/i/logo.gif";

this works in that you get a method called onload on resulting image objects.
It does not work in that you have to cal the method in order for it to fire…

document.images[0].constructor.prototype.onload = function(){alert('yes')};
var t = new Image();
t.src="http://www.cisco.com/web/fw/i/logo.gif";

conclusion: onload != load handler

A coworker was headed into constructor override land:
var imgc = Image.prototype.constructor;
Image = function () {
imgc.apply (this, arguments);
console.log ('ccc', this, this instanceof Image);
var self = this;
setTimeout (function () {
this.addEventListener ("load", function () {
alert ('yes');
}, false);
}, 10);
};


this is why you need the settimeout:

var imgc = Image.prototype.constructor;
Image = function () {
imgc.apply (this, arguments);
console.log ('ccc', this, this instanceof Image);
var self = this;

this.addEventListener ("load", function () {
alert ('yes');
}, false);

};