25

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.

Áxel Costas Pena
  • 4,754
  • 5
  • 26
  • 53
Chris Sobolewski
  • 12,363
  • 12
  • 56
  • 95

2 Answers2

47

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;
}
Community
  • 1
  • 1
Rob W
  • 315,396
  • 71
  • 752
  • 644
  • 2
    PS. `document.appendChild` is an invalid call. `document` is not a node, so you cannot append an element to it. To insert the image in the document, use `document.body.appendChild`. – Rob W Mar 21 '12 at 16:49
  • Thanks, that's what I'm actually doing, just left it out in this by accident. :) – Chris Sobolewski Mar 21 '12 at 16:57
  • FYI: These checks fail in Internet Explorer for SVG graphics, because all the values you are checking are `0`. :-( – Krisztián Balla Feb 04 '20 at 14:09
0

Here is my solution. If I've 404 for my image - I try to insert one of my array that is 200 OK (Pure Javascript). Images must be in same path. Otherwise - my func will return 'no-image.png'. jQuery/JavaScript to replace broken images

Community
  • 1
  • 1