Created
August 22, 2018 20:30
-
-
Save sriramrudraraju/512b153c6cdc8e1375f1ac527c35d178 to your computer and use it in GitHub Desktop.
lazy loading images in react
This file contains 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
// React wrapper for lozad.js for images | |
import * as React from 'react'; | |
import * as lozad from 'lozad'; | |
// src: the image path that will be lazyloaded | |
// customClass: css class that will be applied to img element | |
// defaultImageSrc: image path (preferebly local to this app) that needs to be displayed | |
// by default before the required imgae lazy loaded | |
interface LozadWrapperProps { | |
src: string; | |
customClass: any; | |
defaultImageSrc: string; | |
} | |
class LozadWrapper extends React.Component<LozadWrapperProps> { | |
img: any; | |
constructor(props: LozadWrapperProps) { | |
super(props); | |
this.imageLoaded = this.imageLoaded.bind(this); | |
this.imageRef = this.imageRef.bind(this); | |
} | |
imageRef(el: HTMLImageElement) { | |
this.img = el; | |
} | |
imageLoaded(el: HTMLImageElement) { | |
el.src = this.props.src; | |
} | |
componentDidMount() { | |
const myComponent = this; | |
const observer = lozad(this.img, { | |
load: function(el: HTMLImageElement) { | |
myComponent.imageLoaded(el); | |
} | |
}); | |
observer.observe(); | |
} | |
render() { | |
const { customClass, defaultImageSrc } = this.props; | |
return ( | |
<img | |
ref={this.imageRef} | |
src={defaultImageSrc} | |
className={customClass} | |
/> | |
); | |
} | |
} | |
export default LozadWrapper; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment