Evan Levesque
Evan Levesque

Reputation: 3203

Preload background-image using angularjs promises

How can I preload css background-image's using angularjs promises What I want to do is something that I can use in this way:

link: function(scope, element, attrs){
    element.hide();
    url = attrs.url;
    preload(url).then(function(loadedImageURL){
        element.css({
            background-image: "url('" + loadedImageURL + "')"
        });
    });
    element.fadeIn();
}

Please note that this is not a duplicate question of this one.

Upvotes: 3

Views: 4170

Answers (1)

Ilan Frumer
Ilan Frumer

Reputation: 32357

Try this:

function preload(url) {
  var deffered = $q.defer(),
      image = new Image();

  image.src = url;

  if (image.complete) {

    deffered.resolve();

  } else {

    image.addEventListener('load', function() {
      deffered.resolve();
    });

    image.addEventListener('error', function() {
      deffered.reject();
    });
  }

  return deffered.promise;
}

Upvotes: 7

Related Questions