javascript - Check if image exists with url Doesn't work in all browsers -


hi guys need in project show image other fields in loop image src differs every iteration, , have know if image exists make default src if not, code show works on firefox not in chrome , ie :

  var img = new image();     img.src = "www.imagesource.com/image.jpeg";      var imgcheck = img.width;      if (imgcheck==0) {   alert("you have 0 size image"); } else {    alert('you have img');    //do } 

need helps..

two problems there:

  1. img.src = "www.imagesource.com/image.jpeg" that's relative url, it's meant absolute one. add http://, https://, or // in front of it.

  2. you're not allowing asynchronicity of retrieving image. before setting src (correctly), hook load , error events. load tells worked. error tells didn't. check width won't tell anything, because image (probably) isn't loaded yet.

so:

var img = new image(); img.onload = function() {     // loaded, check `width` if think that's necessary }; img.onerror = function() {     // failed load }; img.src = "http://www.imagesource.com/image.jpeg"; 

note that

  1. we're hooking events before setting src. that's important, particularly if there's chance of image being in cache.

  2. both events happen asynchronously.


Comments

Popular posts from this blog

java - UnknownEntityTypeException: Unable to locate persister (Hibernate 5.0) -

python - ValueError: empty vocabulary; perhaps the documents only contain stop words -

ubuntu - collect2: fatal error: ld terminated with signal 9 [Killed] -