I'm trying to detect when an image is loaded using events (instead of using intervals to check the complete property). I have the following code in place but for some reason this does not fire. I've done the some with the onerror and onabort events as well, just in case if the image fails to load.
Now, if I attach a callback to the image load then the callback is executed, withing printing "Image Loaded" from the prototype's onload. It's almost like the new overridden onload is not called at all. I've made sure this is the first thing in the head script tag.
Image.prototype.coreOnload = Image.prototype.onload;
Image.prototype.onload = function() {
console.log('Image Loaded ' + this.src);
if( this.coreOnload ) {
this.coreOnload();
}
};
Oh I'm testing this is chrome!
Any pointers?
EDIT1: Adding my entire html
When I load this page, "Loaded from callback" is logged but not "Image Loaded". I would expect to see both.
<html>
<head>
<script type="text/javascript" >
Image.prototype.coreOnload = Image.prototype.onload;
Image.prototype.onload = function() {
console.log('Image Loaded ' + this.src);
if( this.coreOnload ) {
this.coreOnload();
}
};
Image.prototype.coreOnerror = Image.prototype.onerror;
Image.prototype.onerror = function() {
console.log('Image Loaded Error ' + this.src);
if( this.coreOnerror ) {
this.coreOnerror();
}
};
Image.prototype.coreOnabort = Image.prototype.onabort;
Image.prototype.onabort = function() {
console.log('Image Loaded Error ' + this.src);
if( this.coreOnabort ) {
this.coreOnabort();
}
};
</script>
<style>
.newStyle {
font-size: 14pt;
}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.3.js"></script>
</head>
<body >
<script type="text/javascript">
var img = new Image();
img.onload = function(){
console.log("Loaded from callback")
};
img.src = "http://i2.cdn.turner.com/cnn/dam/assets/121204012423-obama-boehner-t1-only-t1-main.jpg";
</script>
<a href="http://www.news.com">An external link</a>
</body>
</html>
EDIT: corrected typo in log message.