Giter Site home page Giter Site logo

Comments (3)

AustinGil avatar AustinGil commented on July 27, 2024

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?

from vuetensils.

christophermiles avatar christophermiles commented on July 27, 2024

@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.

from vuetensils.

AustinGil avatar AustinGil commented on July 27, 2024

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.

from vuetensils.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.