简体   繁体   中英

How to detect if the image path is broken?

I am trying to detect if the image is available in javascript .

I have a switch statement which return different type of images.

switch (type){

case 'oldProduct':
return "<img src='project/'" + folder + imagename + "/>"
break;

case 'newProduct':
return "<img src='project/'" + folder2 + imagename2 + "/>"
break;

more cases....

}

I was wondering if there are anyways to detect if the images exist before I return the image. <img src='project/'" + folder2 + imagename2 + "/img> src could be a broken path in my case. Thanks a lot!

If you just wanted to use javascript and not jquery my only suggestion would be to load the image onto the page like

<img src="yoursrc" id="testImage" style="display:none;"/>

then check the onerror method "not may not work in really old ie"

var image = document.getElementById('testImage');
im.onerror = function(){
  //do something on error
};

However a much neater and reliable way would be to run a jquery get on the image.

Like this

function checkImg(src){
   var jqxhr = $.get(src, function() {
     return true;
   }).fail(function() { 
    return false;
   });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM