How do you make React wait for ALL multimedia to be fully loaded?
Asked Answered
E

1

5

I am building a website in ReactJS. The first screen of this site contains three videos. I want to know how I can set up an event that gets triggered when all three videos have been loaded.

My goal is to display my loading animation until all of the videos have successfully loaded (so the user doesn't sit there staring at video containers waiting to be populated). Ideally when the loading animation is complete, the videos will be fully loaded and ready to be played with no UI interruptions.

Using lifecycle hooks for this use case does not seem to work, as these hooks will wait until the DOM has rendered, but not until the multimedia has loaded.

  // Does not work
  // Similar to componentDidMount and componentDidUpdate:
  useEffect(() => {
    setIsLoading(false)
  });

I have seen similar questions mentioning to use the <video> onLoad event:

<video ref={video1}
    autoPlay
    playsInline
    muted
    className="video"
    loop
    src={bike}
    onLoad={()=>{console.log("I don't get called???")}}
/>

but for some reason this function is never called.

This seems like a relatively common use case so I'd highly appreciate advice on the correct solution.

Extra Info:

  • These videos will be locally available (not fetched from an external endpoint)
  • I prefer to stick to using functional components
Extravagate answered 15/1, 2021 at 5:16 Comment(0)
H
10

Try using the "onLoadedData" event.

I wrote a small demo to verify that all three videos have loaded using this event.

Using the onLoadedData event to trigger setVideoLoaded.

      <video
        autoPlay
        playsInline
        muted
        className="video"
        loop
        src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4"
        onLoadedData={() => {
          setVideoLoaded();
        }}
      />

Increment the state each time the event is fired by a video loading. Then do some more stuff when all three are ready to play.

const [loadCount, setLoadCount] = useState(0);

  const setVideoLoaded = () => {
    console.log("video loaded");
    if (loadCount <= 1) {
      setLoadCount(loadCount + 1);
    } else {
      console.log("All videos loaded!");
    }
  };

Horseback answered 15/1, 2021 at 5:28 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.