Last active
January 3, 2020 05:24
-
-
Save avishwakarma/0f56502d7c82c4ceab21cd327d1a1ab8 to your computer and use it in GitHub Desktop.
Lazy load images in Preact using Intersection Observer
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 { h, Component } from 'preact'; | |
| import classy from 'classnames'; | |
| export default class Image extends Component { | |
| state = { | |
| src: 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7', | |
| dataSrc: false, | |
| loaded: false | |
| } | |
| inview(entries, observer){ | |
| entries.forEach(entry => { | |
| if(entry.intersectionRatio){ | |
| entry.target.addEventListener('load', this.loading.bind(this)); | |
| entry.target.src = entry.target.getAttribute("data-src"); | |
| observer.unobserve(entry.target); | |
| } | |
| }) | |
| } | |
| loading(event){ | |
| if(event.target.complete) this.setState({ | |
| loaded: true | |
| }); | |
| } | |
| componentDidMount(){ | |
| this.setState({ | |
| dataSrc: this.props.src, | |
| loaded: false | |
| }); | |
| const observer = new IntersectionObserver(this.inview.bind(this)); | |
| observer.observe(this.element); | |
| } | |
| render() { | |
| return ( | |
| <div className="image-container"> | |
| <div className={classy({loader: true, hidden: this.state.loaded})}><img src="assets/img/loading.svg" /></div> | |
| <img src={this.state.src} data-src={this.state.dataSrc} ref={element => this.element = element} /> | |
| </div> | |
| ); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Any further instruction we need to use it?
Getting error for classy and classname in preact