Detect when an image fails to load in Javascript

2019-01-04 11:56发布

Is there a way to determine if a image path leads to an actual image, Ie, detect when an image fails to load in Javascript.

For a web app, I am parsing a xml file and dynamically creating HTML images from a list of image paths. Some image paths may no longer exist on the server so I want to fail gracefully by detecting which images fail to load and deleting that HTML img element.

Note JQuery solutions wont be able to be used(the boss doesn't want to use JQuery, yes I know dont get me started). I know of a way in JQuery to detect when an image is loaded, but not whether it failed.

My code to create img elements but how can I detect if the img path leads to a failed to load image?

var imgObj = new Image();  // document.createElement("img");
imgObj.src = src;

7条回答
【Aperson】
2楼-- · 2019-01-04 12:37

jQuery + CSS for img

With jQuery this is working for me :

$('img').error(function() {
    $(this).attr('src', '/no-img.png').addClass('no-img');
});

And I can use this picture everywhere on my website regardless of the size of it with the following CSS3 property :

img.no-img {
    object-fit: cover;
    object-position: 50% 50%;
}

TIP 1 : use a square image of at least 800 x 800 pixels.

TIP 2 : for use with portrait of people, use object-position: 20% 50%;

CSS only for background-img

For missing background images, I also added the following on each background-image declaration :

background-image: url('path-to-image.png'), url('no-img.png');

NOTE : not working for transparent images.

Apache server side

Another solution is to detect missing image with Apache before to send to browser and remplace it by the default no-img.png content.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} /images/.*\.(gif|jpg|jpeg|png)$
RewriteRule .* /images/no-img.png [L,R=307]
查看更多
登录 后发表回答