2
<div className="image" style={{ backgroundImage: `url(${entity.image_url})`}} />}

I am setting a background-image by passing the url as an inline style attribute. However, there will be times when the image link is broken. I am familiar with the onerror event of the tag. However I am not familiar with how I can detect a broken link when setting a background image. I was thinking of attempting to load the image in a hidden and use the onerror attribute, but this requires me to load the image twice, which is wasteful. What is a better way to do this?

Anthony O
  • 622
  • 7
  • 26

3 Answers3

1

The old school style is to pre load all images. Preload Images

Now you has the Image in a js object and does not to load the image again or twice. By this you can also check if its broken Detect broken images. And for sure if you use the clever AJAX way of life you can also detect and replace broken images.

Thomas Ludewig
  • 696
  • 9
  • 17
  • 1
    Just a tip. if you store the images in in a fake frameset (just one frame) they will remain even your page content changes. Some thought also by https://www.photo-mark.com/notes/image-preloading/. BTTW: are you sure that your browser doesnt cache them ? – Thomas Ludewig Sep 20 '19 at 20:50
1

why not write some JS and test the entity.image_url. if you don't get an object back it will come up as undefined or null. wrtie an if statement for both to cover the possibilities.

if (entity === undefined || entity === null) {
  //write an error message
} else {
  //drop a dynamic template literal into your html
  //you can either appendChild() or build a string and user innerHTML
}
sao
  • 1,835
  • 6
  • 21
  • 40
1

This is how I was able to do it in React:

 import noImage from <local_image_path>;

 {(entity && entity.image) ?
    <div style={{backgroundImage: `url(${entity.image}), url(${noImage})`}}/> :
    <div style={{backgroundImage: `url(${noImage})`}}/>
  }

This takes care of two cases. Case 1: broken image link. If there is a 404 on the entity.image url, noImage is loaded. Case 2: entity.image is undefined, noImage is loaded.

Anthony O
  • 622
  • 7
  • 26