Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React video loading in memory before rendering to screen

I am having a hard time figuring out how to load a spinner while a video is loading. I don't want to do a DOM loader, I want everything on the page to load up while the video is loading. So far, when I use onLoadStart and onLoadedData, they both seem to fire at the same time as the entire page is done loading. Not helpful.

Is there a way to async load this and show a spinner while loading? Perhaps load into virtual memory or something?

Here is my current code:

"render" function

    const { isLoading } = this.state;

    return (
        <React.Fragment>
            {isLoading && (
                <CircularProgress />
            )}

            <video
                loop
                muted
                autoPlay
                src={WaveVideo}
                preload={'auto'}
                type={'video/mp4'}
                className={classes.video}
                ref={ref => this.headerVideo}
                onLoadStart={() => {
                    console.log('...I am loading...')
                    this.setState({ isLoading: true });
                }}
                onLoadedData={() => {
                    console.log('Data is loaded!')
                    this.setState({ isLoading: false });
                }}>
            </video>
        </React.Fragment>
    );
like image 884
GoreDefex Avatar asked Feb 17 '19 10:02

GoreDefex


1 Answers

Since you have the autoplay attribute included, using the onplay event ought to work for this case. I've modified your original example to demonstrate:

componentDidMount() {
  this.setState({isLoading: true})
}

render() {
    const { isLoading } = this.state;

    return (
        <React.Fragment>
            {isLoading && <CircularProgress />}

            <video
                loop
                muted
                autoPlay
                src={WaveVideo}
                preload={'auto'}
                type={'video/mp4'}
                className={classes.video}
                ref={ref => this.headerVideo}
                onLoadEnd={() => this.setState({isLoading: false})}>
            </video>
        </React.Fragment>
    );
}

So when this component is created it'll run the componentDidMount lifecycle function to set the initial loading indicator state, causing the spinner to render alongside the loading video. We, then, unset the loading indicator state once the video has begun playing on its own, which causes the spinner to no longer render.

EDIT:

I've since learned that the event you are binding in your example onloadeddata "is fired when the first frame of the media has finished loading". This neatly explains why you were seeing both events firing at once. The event you were intending to use was actually onloadend. I've included it in the example, above, replacing the original onplay handler.

like image 144
ant Avatar answered Oct 31 '22 23:10

ant