0
Validating image url.
I'm creating all image elements using js dynamically but some users don't have avatar in their profile. It makes code look bad. how can I know if given image-url is pointing to valid image? If someone has no avatar I can add a default avatar. but I can't determine if user really has avatar or not. code link š : https://code.sololearn.com/WuIQEt1QZlGJ/?ref=app Thanks!
1 Answer
+ 2
Thanks! ćļ¼Øļ¼”ļ¼°ļ¼°ļ¼¹ ļ¼“ļ¼Æ ļ¼Øļ¼„ļ¼¬ļ¼°ć
It's working perfectly.
I would like to add one more point for future reference of others who will search for similar queries.
I found on SO
https://stackoverflow.com/questions/8124866/how-does-one-use-the-onerror-attribute-of-an-img-element
It's necessary to nullify onerror event once it's fired. Otherwise if browser gets error for second time it'll call the same method again and again resulting in infinite iterations.
here is how we can prevent this from happening.
let avt=new Image('100px','100px');
avt.onerror=()=>{
avt.onerror=null;
avt.src="https://www.sololearn.com/Images/NoAvatar.jpg";
/*above is default image*/
}