diff --git a/src/react-image-zoom.js b/src/react-image-zoom.js index 73d51e3..f015aed 100644 --- a/src/react-image-zoom.js +++ b/src/react-image-zoom.js @@ -6,16 +6,19 @@ class ReactImageZoom extends React.Component { constructor(props) { super(props); this.container = undefined; + this.observer = null; this.getRef = this.getRef.bind(this); } componentDidMount() { - this.rerenderImageZoom(this.props); + this.setupLazyLoading(); } UNSAFE_componentWillUnmount() { - this.imageZoom.kill(); - this.imageZoom = void 0; + this.kill(); + if (this.observer) { + this.observer.disconnect(); + } } UNSAFE_componentWillReceiveProps(nextProps) { @@ -25,8 +28,32 @@ class ReactImageZoom extends React.Component { } } + setupLazyLoading() { + if ('IntersectionObserver' in window) { + this.observer = new IntersectionObserver( + (entries) => { + entries.forEach((entry) => { + if (entry.isIntersecting) { + this.rerenderImageZoom(this.props); + this.observer.disconnect(); + } + }); + }, + { rootMargin: '100px' } + ); + + if (this.container) { + this.observer.observe(this.container); + } + } else { + this.rerenderImageZoom(this.props); + } + } + rerenderImageZoom(props) { - this.imageZoom = new ImageZoom(this.container, JSON.parse(JSON.stringify(props))); + if (!this.imageZoom) { + this.imageZoom = new ImageZoom(this.container, JSON.parse(JSON.stringify(props))); + } } setup() { @@ -34,7 +61,10 @@ class ReactImageZoom extends React.Component { } kill() { - this.imageZoom.kill(); + if (this.imageZoom) { + this.imageZoom.kill(); + this.imageZoom = void 0; + } } getRef(ref) { @@ -42,7 +72,7 @@ class ReactImageZoom extends React.Component { } render() { - return