How to lazy load images in Framework7 with AngularJS

So, you’re using Framework7 with Angular and you enabled lazy load feature as described in the docs but it doesn’t work, eh? :)

Well, that’s no wonder if you bound the image url’s via data binding like this:

<img data-src="{{imgurl}}" class="lazy">
 
<script>
  angularApp.controller('controller', ['$scope',
    function ($scope) {
      $scope.imgurl = 'http://path.to/my/image.jpg';
    }
  ]);
</script>

The reason for this is that the url to the image is not set as plain text in the data-src attribute. Instead, it is bound via Angular to a javascript variable. The problem here is that F7 does not know this and tries to set the string ‘{{imgurl}}’ as the url to the image which of course doesn’t work.

The solution to fix lazy load

So, the solution to this is to let Angular handle lazy load of images instead of using F7’s built-in mechanism. To do this you need to download an additional module for Angular. This one did a good job for me: https://github.com/Pentiado/angular-lazy-img

1) Add it to your project:

<script type="text/javascript" src="lib/angular-lazy-img/angular-lazy-img.js"></script>

2) Then, import the module into your app:

var angularApp = angular.module('angularApp', ['angularLazyImg']);

3) As a next step, modify the html img tag (use lazy-img attribute instead of data-src and also remove “lazy” class):

<img lazy-img="{{imgurl}}">

4) Lastly, you need to check if a user has scrolled and then trigger lazy load feature. So, in your controller do this:

Dom7('.page-content').on("scroll", function () {
  $rootScope.$emit('lazyImg:refresh');
});

That’s pretty much it.

Demo app

Happy coding.

One thought on “How to lazy load images in Framework7 with AngularJS

Leave a Reply