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:
img.src = "www.imagesource.com/image.jpeg"that's relative url, it's meant absolute one. addhttp://,https://, or//in front of it.you're not allowing asynchronicity of retrieving image. before setting
src(correctly), hookload,errorevents.loadtells worked.errortells didn't. checkwidthwon'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
we're hooking events before setting
src. that's important, particularly if there's chance of image being in cache.both events happen asynchronously.
Comments
Post a Comment