Questo è in realtà difficile, soprattutto se si intende restituire un URL immagine per casi d'uso in cui è necessario concatenare stringhe con l'URL dell'immagine condizione onerror
, ad es. potresti voler impostare in modo programmatico il parametro url
in CSS.
Il trucco è che il caricamento delle immagini è asincrona per natura in modo che il onerror
non accada sunchronously, vale a dire se si chiama returnPhotoURL
restituisce immediatamente undefined
bcs il metodo asincrono di carico/movimentazione del carico dell'immagine appena iniziata.
Quindi, è davvero necessario avvolgere il copione in una Promessa, quindi chiamarlo come di seguito. NOTA: il mio script di esempio fa alcune altre cose, ma mostra il concetto generale:
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;
}
});
}
fonte
2017-12-15 00:39:24
Questo può essere davvero pericoloso se 'http://placekitten.com/100/100' non esiste, come il browser martello il 'http://placekitten.com/100/100' url continuamente. Vedi http://stackoverflow.com/questions/92720/jquery-javascript-to-replace-broken-images per una soluzione – Neromancer
@Neromancer che ho provato in Chrome: http://jsfiddle.net/GvJh3/1/. Nessun ciclo infinito si verifica. –
@ ŠimeVidas: questo perché Chrome valuta onerror una sola volta, mentre tutti gli altri browser lo fanno continuamente, per evitare che il ciclo assomigli a questo: 'onerror =" this.onerror = null; this.src = 'http: // placekitten .com/100/100 '; "' –