Monday, June 3, 2024
176
rated 0 times [  183] [ 7]  / answers: 1 / hits: 40998  / 12 Years ago, wed, march 21, 2012, 12:00:00

I am trying to append an image to a page using JavaScript:



image = document.createElement('img');
image.onload = function(){
document.body.appendChild(image);
}
image.onerror = function(){
//display error
}
image.src = 'http://example.com/image.png';


The user must be authenticated to see this image, and if they are not, I want to display an error message. Unfortunately, the server is not returning an HTTP error message, but rather redirect the request to a (mostly) empty page, so I am getting an HTTP 200, but the warning Resource interpreted as Image but transferred with MIME type text/html and nothing is displaying.



How can I handle this case? I don't have the ability to change what the webserver serves up if the user isn't authenticated.


More From » error-handling

 Answers
28

In the image.onload event listener, check whether image.width and image.height are both zero (preferably image.naturalWidth and image.naturalHeight, when they are supported).


If the width and height are both zero, the image is considered invalid.


Demo: http://jsfiddle.net/RbNeG/


// Usage:
loadImage('notexist.png');

function loadImage(src) {
var image = new Image;
image.onload = function() {
if ('naturalHeight' in this) {
if (this.naturalHeight + this.naturalWidth === 0) {
this.onerror();
return;
}
} else if (this.width + this.height == 0) {
this.onerror();
return;
}
// At this point, there's no error.
document.body.appendChild(image);
};
image.onerror = function() {
//display error
document.body.appendChild(
document.createTextNode('nError loading as image: ' + this.src)
);
};
image.src = src;
}

[#86693] Tuesday, March 20, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gleng

Total Points: 471
Total Questions: 107
Total Answers: 102

Location: Virgin Islands (U.S.)
Member since Fri, May 7, 2021
3 Years ago
;