I am making a function on Ionic 3 to load user avatar with cache and a default avatar if user did not upload his own avatar. Here is my code follow by this https://gist.github.com/pabloleonalcaide/1e8ece835ea689894dd37a44f0ce7134
public get_UserIcon(id, cache = null) {
cache = cache || Math.floor(new Date().getMinutes() / 6); //cache for 10 minutes
let url = `${server}UserIcon${id}.jpg?c=${cache}`;
let image = new Image();
image.src = url;
if(image.width != 0){ // check if image exist
return url;
}else{
return DefaultImage;
}
}
However, when i try to run the code, the image.width
will show 0 and return the Default image even the image is on the server . Sometime it will show the correct width and return the correct avatar.
I have tried to use
img.onload = () => {
return url;
}
img.onerror = () =>{
return DefaultImage;
}
But i am not sure why using above code will let my app lag, it seem like stuck in the JS runtime stack. I have tried to put a console.log in both onload and onerror but none is been called.
Anyone know how to solve it? Thanks
Update:
My usage would be like this, so that the function will check is the image exist and return the user avatar or a default avatar.
<img [src]="get_UserIcon(id)">