Last active
January 20, 2018 19:53
-
-
Save Dante-101/61cc0376cb01d93707b9adf66c38076e to your computer and use it in GitHub Desktop.
React video element which stops downloading of video on unmount. If the video has been downloaded successfully, there is no effect. It is used to prevent network request backlog of old assets in Single Page Applications (SPA) and Progressive Web Apps (PWA)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import * as React from 'react' | |
| export class VideoComponent extends React.Component<React.HTMLProps<HTMLVideoElement>> { | |
| videoElem: HTMLVideoElement | null | |
| srcElem: HTMLSourceElement | null | |
| componentWillUnmount() { | |
| this.unmountVideo() | |
| } | |
| componentWillReceiveProps(nextProps: React.HTMLProps<HTMLVideoElement>) { | |
| if (nextProps.src != this.props.src) { | |
| this.unmountVideo() | |
| } | |
| } | |
| unmountVideo = () => { | |
| //First remove the src attribute | |
| if (this.srcElem) this.srcElem.removeAttribute('src') | |
| //Reload the video. For some reason, it doesn't work without this. | |
| if (this.videoElem) this.videoElem.load() | |
| } | |
| render() { | |
| //We don't want src in <video> element | |
| const { src, ...p } = this.props | |
| return <video ref={e => this.videoElem = e} {...p}> | |
| <source ref={(elem) => this.srcElem = elem} src={src} type="video/mp4" /> | |
| </video> | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment