Reputation: 3203
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
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