Skip to content

Instantly share code, notes, and snippets.

@adambarthelson
Created August 12, 2014 16:41
Show Gist options
  • Save adambarthelson/c915334f298ae2bf298e to your computer and use it in GitHub Desktop.
Save adambarthelson/c915334f298ae2bf298e to your computer and use it in GitHub Desktop.
Element background image preloader directive
<div bg-preload-src="http://31.media.tumblr.com/tumblr_mac0i9xIMf1rzupqxo1_500.png"></div>
app.directive('bgPreloadSrc', ['preload', function(preload) {
return function(scope, element, attrs) {
element.parent().addClass('loading');
preload(attrs.bgPreloadSrc).then(function(){
element.css({
"background-image": "url('" + attrs.bgPreloadSrc + "')"
});
element.parent().removeClass('loading');
element.parent().addClass('loaded');
});
}
}]);
(function(){
// A utility class for preloading image objects.
var app = angular.module( "Preloader", [] );
app.factory('preload', ['$q', function($q) {
return function(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;
}
}]);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment