IntersectionObserver callback firing immediately on page load IntersectionObserver callback firing immediately on page load javascript javascript

IntersectionObserver callback firing immediately on page load


That is the default behaviour. When you instantiate an instance of the IntersectionObserver, the callback will be fired.

It is recommended to guard against this case.

entries.forEach(entry => {  if (entry.intersectionRatio > 0) {    entry.target.classList.add('in-viewport');  } else {    entry.target.classList.remove('in-viewport');  }});

Also I found this article as well as the docs to be very helpful, specifically about the intersectionRatio or isIntersecting properties on the IntersectionObserverEntry.

· https://www.smashingmagazine.com/2018/01/deferring-lazy-loading-intersection-observer-api/

· https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserver

· https://developer.mozilla.org/en-US/docs/Web/API/IntersectionObserverEntry