0

I want to render my image only when the user has seen it or when the image element is visible within the user viewport. I already tried it, but the image is only rendered when I already passed all the image element, not one by one when i scroll.

I create a custom directive and place it on my parent div.

This is my intersection observer using Vue directive:

inserted: el => {
  let arrayChildren = Array.from(el.children)

  const config = {
    root: null,
    rootMargin: '0px',
    threshold: 1.0,
  }

  let observer = new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        entry.target.src = entry.target.dataset.src
        observer.unobserve(entry.target)
      }
    })
  }, config)

  function getAllImgQuery() {
    let imageArray = []
    arrayChildren.forEach(element => {
      if (element.nodeName === 'IMG') {
        imageArray.push(element)
      }
    })
    return imageArray
  }

  let imageQuery = getAllImgQuery()

  imageQuery.forEach(image => {
    observer.observe(image)
  })
},

And this is my Vue component:

<template>
  <div id="image-container">
    <div class="product">
      <figure class="image-wrapper" v-lazyload>
        <img :data-src="url" style="margin-top: 100px">
        <img :data-src="url" style="margin-top: 100px">
        <img :data-src="url" style="margin-top: 100px">
        <img :data-src="url" style="margin-top: 100px">
        <img :data-src="url" style="margin-top: 100px">
        <img :data-src="url" style="margin-top: 100px">
      </figure>
    </div>
  </div>
</template>

<script>
import lazyLoadDirective from "../directives/lazyLoadImage.js";

export default {
  data() {
    return {
      url:
        "https://s2.reutersmedia.net/resources/r/?m=02&d=20190823&t=2&i=1422065068&w=1200&r=LYNXNPEF7M1OI"
    };
  },
  directives: {
    lazyload: lazyLoadDirective
  }
};
</script>

At the end, the six images loads at the same time only when I already seen it or intersect it (when I was at the bottom of the page). How can i load my image one by one only after i scroll pass it ?

Andrew Vasylchuk
  • 4,671
  • 2
  • 12
  • 30
cantdocpp
  • 350
  • 7
  • 18

1 Answers1

0

I think your problem is related to the threshold you have set. I recommend reading: https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API

Treshold:

Either a single number or an array of numbers which indicate at what percentage of the target's visibility the observer's callback should be executed. If you only want to detect when visibility passes the 50% mark, you can use a value of 0.5. If you want the callback to run every time visibility passes another 25%, you would specify the array [0, 0.25, 0.5, 0.75, 1]. The default is 0 (meaning as soon as even one pixel is visible, the callback will be run). A value of 1.0 means that the threshold isn't considered passed until every pixel is visible.

T. Short
  • 3,481
  • 14
  • 30