AustinGil / vuetensils

🍴 A tasty toolset for Vue.js 🛠 - Lightweight, functional components to boost your next project.
https://vuetensils.austingil.com/
MIT License
658 stars 38 forks source link

Intersect question: how to observe many child elements in v-for loop #116

Open jjjsmit opened 3 years ago

jjjsmit commented 3 years ago

I am very impressed with Vuetensils. I must compliment you on your succinct and well written code.

I'm evaluating the Intersect directive for a case where there are potentially thousands of child elements rendered in a v-for loop. It appears that Intersect creates a new IntersectionObserver in every child element. As I read the Intersection Observer API docs, the intended pattern is to create an Intersection Observer in the parent and .observe() each of the child elements as a target.

Please correct me if I'm wrong, Could you point me to an example using Intersect in this scenario? Thank you very much.

AustinGil commented 3 years ago

Hey, thank you very much. This is a very good question, but not one I have an answer quite ready for. You are absolutely right that IntersectionObserver is intended to support observing multiple targets. However, I dont think that was my intention with this component. At the time I created it, there wasn't a clear way I could think of to specify which elements to target.

I think it's possible now to provide a CSS style selector as the target and then do a query selector for those, but the support is not currently there.

Could you do me a favor and create a minimal example on Codesandbox and maybe I can work something into the library to support your needs?

christophermiles commented 3 years ago

@jjjsmit I encountered a similar issue in a custom component library I was writing for the project I work on; I wanted a component that could report when it was scrolled in and out out of view. The problem I encountered was when wanting to use this in a list, eg. to lazy load images in a series of newsfeed posts. I realised it would be inefficient to create an observer for each image.

In the end I wrote a directive I could use for each use case, in this case lazy loading of images:

let lazyImageObserver = null

if ('IntersectionObserver' in window) {
  lazyImageObserver = new IntersectionObserver(
    (entries, observer) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          handleLazyImageLoading(entry.target)

          lazyImageObserver.unobserve(entry.target)
        }
      })
    },
    {
      rootMargin: '0px 0px 300px 0px', // So that lazy images begin loading when they approach within 200px of the bottom of the view
    }
  )
}

function handleLazyImageLoading(element) {
  if (
    'lazyImgSrc' in element.dataset &&
    element.dataset.lazyImgSrc !== ''
  ) {
    element.setAttribute('src', element.dataset.lazyImgSrc)

    element.removeAttribute('data-lazy-img-src')
  }

  if (
    'lazyBackgroundImgSrc' in element.dataset &&
    element.dataset.lazyBackgroundImgSrc !== ''
  ) {
    element.style.backgroundImage = `url(${element.dataset.lazyBackgroundImgSrc})`

    element.removeAttribute('data-lazy-background-img-src')
  }
}

const LazyLoadingImgDirective = {
  install(Vue) {
    Vue.directive('lazy-load-img', (el, binding) => {
      if (binding.value !== binding.oldValue) {
        if (binding.modifiers.background) {
          el.setAttribute('data-lazy-background-img-src', binding.value)
        } else {
          el.setAttribute('data-lazy-img-src', binding.value)
        }

        if ('IntersectionObserver' in window) {
          lazyImageObserver.observe(el) // This will call `handleLazyImageLoading` method when the element scrolls into view
        } else {
          handleLazyImageLoading(el)
        }
      }
    })
  }
}

export default LazyLoadingImgDirective

I wrote another one for lazy loading YouTube videos:

import fitvids from 'fitvids'

let lazyIframeObserver = null

if ('IntersectionObserver' in window) {
  lazyIframeObserver = new IntersectionObserver(
    (entries, observer) => {
      entries.forEach(entry => {
        if (entry.isIntersecting) {
          handleLazyIframeLoading(entry.target)

          lazyIframeObserver.unobserve(entry.target)
        }
      })
    },
    {
      rootMargin: '0px 0px 300px 0px', // So that lazy iframes begin loading when they approach within 200px of the bottom of the view
    }
  )
}

function handleLazyIframeLoading(iframe) {
  if (
    'lazyIframeSrc' in iframe.dataset &&
    iframe.dataset.lazyIframeSrc !== ''
  ) {
    iframe.setAttribute('src', iframe.dataset.lazyIframeSrc)

    if (iframe.dataset.lazyIframeSrc.includes('youtube')) {
      fitvids({
        players: `iframe[src="${iframe.dataset.lazyIframeSrc}"]`
      })
    }

    iframe.removeAttribute('data-lazy-iframe-src')
  }
}

const LazyLoadingIframeDirective = {
  install(Vue) {
    Vue.directive('lazy-load-iframe', (iframe, binding, vnode) => {
      if (binding.value && binding.value !== binding.oldValue) {
        iframe.setAttribute('data-lazy-iframe-src', binding.value)

        if ('IntersectionObserver' in window) {
          lazyIframeObserver.observe(iframe) // This will call `handleLazyIframeLoading` method when the element scrolls into view
        } else {
          handleLazyIframeLoading(iframe)
        }
      }
    })
  }
}

export default LazyLoadingIframeDirective

This has provided reusability (and some flexibility) without the performance issue of wrapping the code up in a component and generating an observer for each instance of the component.

Not sure if this is the perfect solution might it may lead to some ideas.

AustinGil commented 3 years ago

Thanks for the help here @christophermiles. This is a good solution if the same intersection observer can be used for every intersection event. As a library author, it's hard to do things that way because it's not as flexible. However, it does give me the idea that maybe the user could somehow optionally provide an intersection observer to the library. So if one is provided, it will reuse that one. And if not, it will generate a new one.

Alternatively, I think a good approach is to accept a list of nodes to watch, or a CSS style selector.