JS preload image 'bug' in Opera

I have recently attempted to load an image in JavaScript (using jQuery) and once loaded get it’s dimensions.

Using the following code I managed to successfully read the width and height properties in FireFox 2/3, IE 6/7, Windows Safari 3/4 and Google Chrome, but the dimensions were not available in Opera (10).

$('')
	.load(function() {
		$('body').append(this);
		var w = this.width;
		var h = this.height;
		//..
	})
	.error(function() {
		//..
	})
	.attr('src', '/path/to/image.jpg');

After a fair bit of time playing around trying to debug this small snippet of code, I eventually discovered that if the image was appended to the DOM after the width and height had been read then Opera would report the values correctly.

		var w = this.width;
		var h = this.height;
		$('body').append(this);
		//..

Simply moving line 3 down to below the reading of dimensions solved this issue.

Leave a Reply