image.onError event never fires, but image isn't valid data - need a work around

后端 未结 2 1088
小鲜肉
小鲜肉 2020-11-30 04:54

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

image = document.createElement(\'img\');
image.onload = function(){
    document.body.appendChild(         


        
2条回答
  •  被撕碎了的回忆
    2020-11-30 05:41

    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;
    }
    

提交回复
热议问题