在渲染到屏幕之前在内存中响应视频加载

Gor*_*fex 6 asynchronous loading html5-video reactjs

我很难弄清楚如何在加载视频时加载微调器。我不想做 DOM 加载器,我希望在加载视频时加载页面上的所有内容。到目前为止,当我使用onLoadStartand 时onLoadedData,它们似乎在整个页面加载完成的同时触发。没有帮助。

有没有办法异步加载它并在加载时显示微调器?也许加载到虚拟内存中?

这是我当前的代码:

“渲染”功能

    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>
    );
Run Code Online (Sandbox Code Playgroud)

ant*_*ant 10

由于您已autoplay包含该属性,因此使用该onplay事件应该适用于这种情况。我修改了您的原始示例来演示:

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}
                onCanPlayThrough={() => this.setState({isLoading: false})}>
            </video>
        </React.Fragment>
    );
}
Run Code Online (Sandbox Code Playgroud)

因此,当创建此组件时,它将运行componentDidMount生命周期函数来设置初始加载指示器状态,从而使微调器与加载视频一起渲染。然后,一旦视频开始自行播放,我们就取消加载指示器状态,这会导致旋转器不再渲染。

编辑:

我后来了解到,您在示例中绑定的事件onloadeddata“在媒体的第一帧完成加载时触发”。这巧妙地解释了为什么您会看到两个事件同时触发。您打算使用的事件实际上是onloadend. 我已将其包含在上面的示例中,替换了原始onplay处理程序。