Add a "strict" version of IntersectionObserver.
IntersectionObserver is lazy and only triggers an event when the user stops scrolling or pauses, but sometimes this is impractical because you need to trigger an event as the item comes into view immediately (Notice the choppy animation on the second page on aaha.co or how we detect a slide scrolling into view for ad lazy-loading on casper)
The goal is to create a very simple util that gives a basic scroll-based event class a somewhat-compatible API as IntersectionObserver.
Therefore:
- Instantiate the class with
new StrictIntersectionObserver(callback, options = {})
- Have a function
observe(Element)
to add the element to the list - Have a function
unobserve(Element)
to remove the element from watched list - Have a function
disconnect()
to remove all event listeners and watched elements. - Keep a property that has a list of these elements, when adding cache the bounds of the object, update the bounds on document resize event.
- On scroll, check to make sure it's not intersecting with a very short debounce (50ms)
- For all items that are intersecting, instantiate an
IntersectionObserverEntry
wrapper for them, and trigger the callback for the items. (isIntersecting
must always be true) - Do not worry about calculating intersecting ratio etc
Now the important one.
- Do not create a separate scroll event listener for each instance of
StrictIntersectionObserver
. The goal is to be able to make many different instances with different callbacks. We don't want to have 5 different scroll listeners each running and recalculating the same things. This is why we can't just use the polyfill.
Some of this code can be reused from @aaha/polyfills/polyfills/intersection-observer.js
We ARE NOT MAKING A POLYFILL. The StrictIntersectionObserver
will be used on browsers that are compatible with IntersectionObserver. We could use the polyfill as StrictIntersectionObserver
but that isn't the goal. The goal is to have a similar interface so we can instantiate one or the other in our specific use-cases.