Last active
January 20, 2018 13:52
-
-
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)
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 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