Search code examples
reactjslazy-loadingautoplay

how to load autoplaying video after the initial load in reactjs?


So i have a video that is autoPlayed and playsinline in an index page, every time i visit the page on mobile, it takes a little longer than other pages and that is obviously because the other pages don't have an autoplayed video in them.

what i want to do is to delay the loading of the video until the page (DOM) is fully loaded, in other words i don't want to reduce the loading time by first loading only the low weight assets, then after loading DOM I want the video to load and auto play.

is this possible in reactjs?

this is the web page using the video


Solution

  • You can use useEffect to play the video after the initial js load.

    function MyVideoComponent() {
      const videoRef = useRef(null);
      useEffect(() => {
        if(videoRef){
          videoRef.current.play();
        }
      }, []);
      return (
        <>
          <video ref={videoRef} />
        </>
      );
    }