Skip to content

Instantly share code, notes, and snippets.

@sriramrudraraju
Created August 22, 2018 20:30
Show Gist options
  • Save sriramrudraraju/512b153c6cdc8e1375f1ac527c35d178 to your computer and use it in GitHub Desktop.
Save sriramrudraraju/512b153c6cdc8e1375f1ac527c35d178 to your computer and use it in GitHub Desktop.
lazy loading images in react
// 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