angularjs - Is it possible to return wether or not an image has loaded in javascript -


i'm (attempting) working on function right return whether or not user has gravatar. javascript limited cross-site checks feels kinda hacky. i'm writing in django use , write api for... i'd rather see if there way client side instead of server side, maybe that's wrong mentality.

this being written in angular directive; i've came far.

 $scope.hasavatar = function(user) {       if (user === undefined)          return false;       var url = 'http://www.gravatar.com/avatar/' + md5(user.email);       var image = new image();      image.onload = function() {          return true;      }      image.onerror = function() {          return false;      }      image.src = url + "?d=404"; } 

i'm still learning javascript. know because of nature of javascript doesn't wait call onload or onerror, completes function, defaults false.

am barking wrong tree trying solve way? or possible callbacks or promises? appreciate help.

you should promise since image loading async:

$scope.hasavatar = function(user) {     var dfd = $q.defer();     if (user === undefined)        return $q.when(false);      var url = 'http://www.gravatar.com/avatar/' + md5(user.email);      var image = new image();     image.onload = function() {        dfd.resolve(true);     }     image.onerror = function() {        dfd.resolve(false);     }     image.src = url + "?d=404";     return dfd.promise; } 

then call this

$scope.hasavatar(user).then(function(hasavatar) {    // logic here. perhaps bind showavatar    $scope.showavatar = hasavatar; }); $scope.showavatar = false; 

Comments

Popular posts from this blog

Java 3D LWJGL collision -

spring - SubProtocolWebSocketHandler - No handlers -

methods - python can't use function in submodule -