0

I am currently trying to implement lazy loading using the IntersectionObserver in my angularjs app.

But when I scroll up and down it doesn't always call the callback function of the observer.

My directive looks like this:

var app = angular.module("test", []);

app.directive("inViewport", function() {
  return {
    restrict: "A",
    link: function(scope, element, attrs) {    
      const observer = new IntersectionObserver(callback);
      const img = angular.element(element)[0];
      observer.observe(img);

      function callback(changes) {
        changes.forEach(change => {
          change.target.classList.toggle(
            "visible",
            change.intersectionRatio > 0
          );
        });
      }
    }
  };
});

See this pen for a demo.

Dominik G
  • 1,459
  • 3
  • 17
  • 37

1 Answers1

2

Use change.isIntersecting instead of change.intersectionRatio > 0 in change.target.classList.toggle

As IntersectionObserver is working in an asynchronous way little laggy will be there on call of the callback function.

var app = angular.module("test", []);

app.directive("inViewport", function() {
  return {
    restrict: "A",
    link: function(scope, element, attrs) {
      
      const observer = new IntersectionObserver(callback);
      
      const img = angular.element(element)[0];
      observer.observe(img);

      function callback(changes) {
        changes.forEach(change => {
          change.target.classList.toggle(
            "visible",
            change.isIntersecting
          );
        });
      }
    }
  };
});
.main div {
  background: green;
  height: 100px;
  width: 100%;
  margin: 10px;
}
    
.main div.visible {
  background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.17/angular.min.js"></script>


<div ng-app="test" class="main">
  <div in-viewport=""></div>
  <div in-viewport=""></div>
  <div in-viewport=""></div>
  <div in-viewport=""></div>
  <div in-viewport=""></div>
  <div in-viewport=""></div>
  <div in-viewport=""></div>
  <div in-viewport=""></div>
  <div in-viewport=""></div>
  <div in-viewport=""></div>
</div>
kalai
  • 41
  • 6