Skip to content

Instantly share code, notes, and snippets.

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

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

Select an option

Save Dante-101/2b95e9ba1e24ade7a43e799f7197976f to your computer and use it in GitHub Desktop.
React image element which stops downloading of image on unmount. If the image 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 ImageComponent extends React.Component<React.HTMLProps<HTMLImageElement>> {
imgElem: HTMLImageElement | null
componentWillUnmount() {
this.unmountImage()
}
componentWillReceiveProps(nextProps: React.HTMLProps<HTMLImageElement>) {
//unmount the old image when a new image is being mounted
if (nextProps.src != this.props.src)
this.unmountImage()
}
unmountImage = () => {
//removing 'src' attribute will stop downloading of the image.
if (this.imgElem)
this.imgElem.removeAttribute('src')
}
render() {
return <img {...this.props} ref={(elem) => this.imgElem = elem} />
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment