Performance: Intersection Observer V.S Scroll Event Listeners

Performance: Intersection Observer V.S Scroll Event Listeners

With the advent of the Intersection Observer through the Observer API, fully supported by modern browsers, the fundamental question I was plagued with was if it indeed the better alternative to scroll listeners from a performance perspective. Prior to tacking that question though, what is the Intersection Observer? Well, in the liberty of my own words it basically facilitates the firing of callback functions when specified DOM elements intersect each other or protrude into the viewport. The observer accepts two arguments which are the callback function itself and the options which contain the root (which equates to the viewport when set to null) and the threshold that specifies how much in percentage the callback should be triggered when the target element protrudes the viewport shown below

carbon (4).png

I’ve also tried to elaborate this further in the below visualization where the red content is the target element and the callback function will only trigger when it reaches the given threshold.

Group 14.png

The distinguishable difference between a scroll listener and the Intersection Observer is the scroll listeners obligation to trigger off at even the slightest movement of a scroll. This happens every single time until the given callback function condition is met and executed (and still continue unless the event listener is removed). Now as you may imagine, that is certainly not efficient for performance especially for mobile. In contrast with the Intersection Observer which fires off its callback function once when the threshold is breached when the target element enters the viewport and at the given threshold and once more when the target element disappears out of the viewports sight. This now make the Intersection Observer a real hero in executing tasks such as reporting the visibility of ads in order to calculate ad revenue, lazy loading images/sections, infinite scrolling and complex animation sequences.

CONCLUSION Although the Intersection Observer is the clear victor in providing better performance, it certainly might not be a viable alternative in certain scenarios but for the fundamental goal of achieving tasks such as altering styles based on scrolling and position, the Intersection Observer is certainly better and should be preferred when performance is imperative.