AngularJS - Single Page Application and lazy loading images

April 06, 2014 - IT

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 skipinvisible option. Lazdy Load script does not work out of the box with AngularJS single page application without skipinvisible as false. It does not show images because i didn't set width and height for images. With skip_invisible: true everything works correctly.