April 6, 2014

November 25, 2019

AngularJS - Single Page Application and lazy loading images

On one of my sites i wanted to use jquery lazy load script.

bower install jquery.lazyload --save

I have spent some time on trying to run in correctly on single page application. Below is a code of directive.

angular.module("myApp").directive("lazy", function($timeout) {
return {
restrict: "C",
link: function(scope, elm) {
$timeout(function() {
$(elm).lazyload({
effect: "fadeIn",
effectspeed: 500,
skip_invisible: false,
})
}, 0)
},
}
})

How to use it:

<img
class="lazy"
ng-src="/images/loader-circle-image.gif"
data-original="{{ item.image_resized }}"
/>

One thing about skip_invisible option. Lazdy Load script does not work out of the box with AngularJS single page application without skip_invisible as false. It does not show images because i didn't set width and height for images. With skip_invisible: true everything works correctly.

© 2020 Przemysław Kołodziejczyk