0

I have an array of image links that I'm getting from reddit, but some image urls are broken. I want to skip over broken image links.

This thread suggested using .width to see if an image exists. I tried using this answer to wait for image links to load before executing code but it's not working, it's skipping right over my if(this.width>0) check.

var imgLinksArray = Array.from(imgLinks);
document.getElementById('photoGrid').innerHTML = "";
for (i = 0; i < imgLinks.length; i++) {
  var workingImgLink = imgLinksArray[i]

  var img = new Image();
  img.onload = function() {
    console.log(this);
    console.log(this.src + " Width: " + this.width);
    for (i = 0; i < imgLinks.length; i++) {
      var workingImgLink = imgLinksArray[i]

      if (this.width > 0) {
        console.log(this.width);
        if (workingImgLink.search("webm") >= 0) {
          document.getElementById('photoGrid').innerHTML += '<video autoplay loop class="box-wrapper"> <source  type="video/webm" src= "' + workingImgLink + '" data-url= "' + workingImgLink + '" class="box" style=background-image:url("' + workingImgLink + '")></video>';
        } else {
          document.getElementById('photoGrid').innerHTML += '<div class="box-wrapper"> <div  data-url= "' + workingImgLink + '" class="box" style=background-image:url("' + workingImgLink + '")></div></div>';

        }
      }
    }

  }
  img.src = workingImgLink;
  var bgImgWidth = img.width;
  var bgImgHeight = img.height;

}

I only want to execute the innerHTML code if I know the image exists. Any suggestions about how to go about this?

0 Answers0