Skip to content

Instantly share code, notes, and snippets.

@Dante-101
Last active January 20, 2018 19:53
Show Gist options
  • Select an option

  • Save Dante-101/61cc0376cb01d93707b9adf66c38076e to your computer and use it in GitHub Desktop.

Select an option

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)
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