This is actually tricky, especially if you plan on returning an image url for use cases where you need to concatenate strings with the onerror
condition image URL, e.g. you might want to programatically set the url
parameter in CSS.
The trick is that image loading is asynchronous by nature so the onerror
doesn't happen sunchronously, i.e. if you call returnPhotoURL
it immediately returns undefined
bcs the asynchronous method of loading/handling the image load just began.
So, you really need to wrap your script in a Promise then call it like below. NOTE: my sample script does some other things but shows the general concept:
returnPhotoURL().then(function(value){
doc.getElementById("account-section-image").style.backgroundImage = "url('" + value + "')";
});
function returnPhotoURL(){
return new Promise(function(resolve, reject){
var img = new Image();
//if the user does not have a photoURL let's try and get one from gravatar
if (!firebase.auth().currentUser.photoURL) {
//first we have to see if user han an email
if(firebase.auth().currentUser.email){
//set sign-in-button background image to gravatar url
img.addEventListener('load', function() {
resolve (getGravatar(firebase.auth().currentUser.email, 48));
}, false);
img.addEventListener('error', function() {
resolve ('//rack.pub/media/fallbackImage.png');
}, false);
img.src = getGravatar(firebase.auth().currentUser.email, 48);
} else {
resolve ('//rack.pub/media/fallbackImage.png');
}
} else {
img.addEventListener('load', function() {
resolve (firebase.auth().currentUser.photoURL);
}, false);
img.addEventListener('error', function() {
resolve ('https://rack.pub/media/fallbackImage.png');
}, false);
img.src = firebase.auth().currentUser.photoURL;
}
});
}