stickymate icon indicating copy to clipboard operation
stickymate copied to clipboard

IntersectionObserver

Open michaelrafailyk opened this issue 3 years ago • 4 comments

Starting work on alternate way of watching elements with using Intersection Observer to avoid constant listening to the scroll event.

michaelrafailyk avatar Jan 15 '21 12:01 michaelrafailyk

I tried next scheme. When the Observer starts to see an element in the viewport, the window scroll event listener starts to watch this element. When an element leaves the viewport, the listener been removed. I believe it's good for performance.

The first tests revealed possible problems. If the transformation moves the element horizontally outside the viewport, the element can never go back, since the Observer will not see it when scrolling vertically. 😕 problem-explanation

michaelrafailyk avatar Jan 15 '21 21:01 michaelrafailyk

All right, we can add rootMargin with 0px 100vw to IntersectionObserver, it is extend range of watching horizontally.

problem-explanation

1 situation. Element outside of viewport horizontally (but in range of rootMargin). Parent of element and every elements upper including body have overflow: auto (it mean default). The observer sees the element. Work well👌But devs will avoid this situation because page will have horizontal scrollbar 😕

2 situation. Element outside of viewport horizontally (but in range of rootMargin). Parent of element or one of upper elements have overflow: hidden. It’s no horizontal scrollbar now but IntersectionObserver can't see this element because it is out of document layout 😕

michaelrafailyk avatar Jan 15 '21 22:01 michaelrafailyk

One more way how to watch element out of viewport.

  • Use a while to check if either parent has an overflow: hidden.
  • If yes – we create a new fake element with position: absolute pointer-events: none left: 0px top: 0px width: 100% height: 100% and place it before our original element (that can be out of viewport).
  • Link original element to fake element any way you decide (property with unique name, for example).
  • Place fake element to IntersectionObserver instead of original element.

Pros: Observer watching of fake element that is possible to observe. Cons: Additional elements in DOM.

problem-explanation-4

michaelrafailyk avatar Jan 17 '21 15:01 michaelrafailyk

I figured out, when scrolling fast, Intersection Observer is missing a moment of intersection about 1/4 of second. It mean if user scrolling very fast he can loose a first frames of animation when element appearing on the viewport. So yes, reaction is not up in time and people on the web telling about it. May be it is not a problem, keep watching.

michaelrafailyk avatar Feb 04 '21 21:02 michaelrafailyk