Angular background image lazy laoder
Lazily load your images
HTML
<div ng-app="angular-lazy">
<div lazy-class="full" lazy-loader="#sampleLoader" lazy-background="http://upload.wikimedia.org/wikipedia/commons/9/97/The_Earth_seen_from_Apollo_17.jpg" class="img"></div>
<div lazy-class="full" lazy-loader="#sampleLoader" lazy-background="http://4.bp.blogspot.com/_pKFEEX6T1AU/S8S9RqSzYcI/AAAAAAAAACE/__q43tvl6nU/s1600/earth.gif" class="img2"></div>
</div>
CSS
.img {
background-image: url("https://i.giphy.com/3oEjI6SIIHBdRxXI40.gif");
background-color: transparent;
width:100px;
height:100px;
}
.img2 {
background:red;
width:100px;
height:100px;
}
.full {
background-size:cover;
background-position:center center;
background-repeat:no-repeat;
}
.hide {
display:none;
}
JavaScript
angular.module('angular-lazy', []).
directive('lazyBackground', ['$document', function($document) {
return {
restrict: 'A',
link: function(scope, iElement, iAttrs) {
var src = iAttrs.lazyBackground + '?r=' + Math.random();
var img = document.createElement('img');
img.onload = function() {
if (angular.isDefined(iAttrs.lazyClass)) {
iElement.addClass(iAttrs.lazyClass);
}
iElement.css({
'background-image': 'url(' + this.src + ')'
});
delete this;
};
img.src = src;
}
}
}]);