vanilla-lazyload: How to handle missing image

Having trouble making this work.

Before using lazyload and srcset, I set fallback and error images using onerror like this:

<img src="logo.svg" onerror="this.src='logo.png'">

I tried doing the same with lazyload setup, trying this.src, this.srcset, this.data-src, this.data-srcset… Tried combining them, tried targeting both the source tag and img but nothing worked. Not sure if onerror fails with srcset and picture or if it’s because of the data attributes being used.

I just want to show a specific error image of the image can’t be loaded or doesn’t exist.

Thanks

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 15 (7 by maintainers)

Most upvoted comments

So say you have a broken image like the following:

<img 
  alt="this should error" 
  class="lazy"
  data-src="https://www.dksahdlfkdjhsf.com/kldasjfdlkfj.jgp">

You can replace its broken image at load error with this:

const yourLazyLoadInstance = new LazyLoad({
  // other settings here...
  callback_error: (img) => {
    img.setAttribute("src", "logo.png");
  }
});

The key point here is to pass that callback_error in LazyLoad options.

callback_error: (img) => {
  img.setAttribute("src", "logo.png");
}

Find a working demo here on Codepen (just made it for you).

Let me know how that works!