Pepperfry Sanjay Jun 20, 2023

Intersection Observer API for Element Visibility Detection and Improved Performance

Article Summary

Pepperfry's engineering team was facing system hangs and 28% CPU usage just from scrolling. The culprit? Traditional scroll event listeners that were choking their main thread.

The Pepperfry team shares how they tackled performance issues on their image-heavy e-commerce listing pages. Their solution involved replacing scroll listeners with the Intersection Observer API for lazy loading, infinite scroll, and sticky elements.

Key Takeaways

Critical Insight

Switching from scroll event listeners to Intersection Observer API cut CPU usage by 20% and dramatically improved scrolling performance on Pepperfry's product pages.

The article includes side-by-side code comparisons showing exactly how they refactored their sticky button functionality with just a few lines of code.

About This Article

Problem

Pepperfry's Studio page kept freezing because scroll event listeners were constantly checking which elements were visible on screen. This happened during infinite scrolling and lazy image loading, which caused CPU usage to spike.

Solution

The team switched from scroll event listeners to the Intersection Observer API. This API watches for visibility changes asynchronously using threshold-based callbacks, so it doesn't need to run continuous DOM queries.

Impact

After using Intersection Observer, scripting time dropped from 28% to 23% and CPU utilization fell by at least 20%. The page felt much more responsive when users scrolled.