Is there is any way to add Lazy Loading for video tag with JavaScript?

Viewed 57

At the moment, I am working on a project that requires me to add three videos to the homepage, but loading them all at once will reduce the load time considerably.

Also i want to use <video/> tag instead of using <iframe/> because i want that autoplay functionality. What's the best way to do this in React? Using NextJS and Chakra UI.

2 Answers

You can use IntersectionObserver and do it as below. For React all you have to do is to add the below code in an useEffect with empty dependency.

const video = document.querySelector("video");

function handleIntersection(entries) {
  entries.map(async (entry) => {
    if (entry.isIntersecting) {
      const res = await fetch("/video.mp4");
      const data = await res.blob();
      video.src = URL.createObjectURL(data);
    }
  });
}

const observer = new IntersectionObserver(handleIntersection);
observer.observe(video);
<video autoplay muted loop playsinline></video>

Also I used a video with a relative path to avoid possible CORS issues.

i found a way to do it using '@react-hook/intersection-observer'

import useIntersectionObserver from '@react-hook/intersection-observer'
import { useRef } from 'react'

const LazyIframe = () => {
  const containerRef = useRef()
  const lockRef = useRef(false)
  const { isIntersecting } = useIntersectionObserver(containerRef)
  if (isIntersecting) {
    lockRef.current = true
  }
  return (
    <div ref={containerRef}>
      {lockRef.current && (
        <video
          src={"add video source here"}
          type="video/mp4"
        ></video>
      )}
    </div>
  )
}


Related