Member-only story

Javascript Intersection Observer

Re-write your scrolling functions for better performance.

Alex Z
3 min readJul 25, 2021
credit: Denys Nevozhai, unsplash.com

The Intersection observer API allows you to determine when and how much of an element is visible inside another element. This new API replaces the scroll handler API in many cases. The top use cases for the intersection observer are:

  1. Sticky navigation bars
  2. Live table of contents
  3. Some scrolling effects
credit: https://aggelosarvanitakis.medium.com

Though a bit more complicated to wrap your head around, the new API performs significantly better than alternate approaches, as measured by percentage of time spent by the browser running JS code in live scrolling scenarios. The alternate approach is performing height and width calculations during scroll handler functions. MDN says about these alternate approaches:

Historically, detecting visibility of an element, or the relative visibility of two elements in relation to each other, has been a difficult task for which solutions have been unreliable and prone to causing the browser and the sites the user is accessing to become sluggish. — Mozilla

Using the…

--

--

Alex Z
Alex Z

Written by Alex Z

Software Developer + Product Manager. Interested in Travel, Culture, Economics and the Internet. Join Medium: https://tinycode.medium.com/membership

No responses yet