From 6d8cf18d0a6cf419fda09689155fc9878255a620 Mon Sep 17 00:00:00 2001 From: Ayush4158 Date: Fri, 3 Oct 2025 20:11:23 +0530 Subject: [PATCH] Imlemented Lazy Loading --- src/react-image-zoom.js | 44 ++++++++++++++++++++++++++++++++++------- 1 file changed, 37 insertions(+), 7 deletions(-) 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
; + return
; } } @@ -55,7 +85,7 @@ ReactImageZoom.propTypes = { offset: PropTypes.object, zoomStyle: PropTypes.string, zoomLensStyle: PropTypes.string, - zoomPosition: PropTypes.oneOf(['top', 'left', 'bottom', 'right', 'original']) + zoomPosition: PropTypes.oneOf(['top', 'left', 'bottom', 'right', 'original']), }; export default ReactImageZoom;