liqvidjs / liqvid

Library for interactive videos in React
https://liqvidjs.org
MIT License
761 stars 39 forks source link

How to preload all static assets like video/image before rendering in client end? #22

Closed rahulmehra0397 closed 2 years ago

rahulmehra0397 commented 2 years ago

Is there a way to load all the videos/images before rendering in the browser, because currently the player is running while the video is not loaded. Hence, the video is not in sync with the player time.

tomByrer commented 2 years ago

Load the assets in a promise, .then run Liqvidjs?

ysulyma commented 2 years ago

You can use obstructCanPlay/obstructCanPlayThrough on the <Video> element, then use the canPlay/canPlayThrough promise on the player:

import {Player, Video, usePlayer} from "liqvid";

function Lesson() {
  return (
    <Player script={script}>
      <LoadingScreen/>
      <Video
        obstructCanPlayThrough
        src="https://www.example.com/video.mp4" start={0}/>
    </Player>
  );
}

function LoadingScreen() {
  const player = usePlayer();
  const [ready, setReady] = useState(false);

  useEffect(() => {
    player.canPlayThrough.then(() => setReady(true));
  }, []);

  if (ready) {
    return null;
  } else {
    return (<div className="loading-screen"></div>);
  }
}

Then you would style .loading-screen to display a loading message/spinner/etc.

These listen to the canplay and canplaythrough events, respectively. This also works for <Audio> elements, but there is no analogue for <img> elements.

@tomByrer's solution would also work.

rahulmehra0397 commented 2 years ago

@ysulyma yes that worked thanks

anishg-cn commented 1 year ago

@ysulyma will the obstructCanPlay work in the case where user seeks forward in the video as well?