Oneezy
Oneezy

Reputation: 5023

Test to see if an image with json value is broken/ or not there and replace with "no-photo" image?


My team and I are using a backend service to grab json data to display images on the frontend. We have a javascript that will display a "no-photo.png" image when their is no value and display the normal product image when their is a value.

The problem is that we will get back values, but the images come back broken because they are not actually there and we have no way of manually removing them.

My question is:
Is their a way to determine if the image is broken even if the image has a value?

Upvotes: 0

Views: 274

Answers (1)

Joseph Silber
Joseph Silber

Reputation: 220026

Set an onerror callback:

var img = new Image();
img.onerror = function () {
    this.src = 'noimage.jpg';
};
img.src = 'path/from/json/img.jpg';

Upvotes: 2

Related Questions