-
-
Save jameswquinn/615e1547d99c99e24528971e4c2b6ce6 to your computer and use it in GitHub Desktop.
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
// IntersectionObserver polyfill | |
import 'intersection-observer' | |
// ***************************** | |
import React, { Component } from 'react' | |
export default class ImageLazyLoader extends Component { | |
state = { | |
isLoaded: false, | |
isVisibleEnough: false | |
} | |
componentDidMount() { | |
let options = { | |
root: null, | |
rootMargin: '0px', | |
threshold: 0.8 | |
} | |
let observer = new IntersectionObserver(this.intersectionObserverCallback, options) | |
let target = document.getElementById(this.props.id) | |
observer.observe(target) | |
} | |
intersectionObserverCallback = (entries, observer) => { | |
entries.forEach(entry => { | |
if (entry.intersectionRatio > 0.8) { | |
this.setState({ | |
isVisibleEnough: true | |
}) | |
observer.unobserve(entry.target) | |
} | |
}) | |
} | |
generanteBluredImage = (link) => { | |
let [before, after] = [...link.split('upload/')] | |
return before + 'upload/e_blur:500,c_scale,h_10/' + after | |
} | |
imageLoaded = () => { | |
this.setState({ | |
isLoaded: true | |
}) | |
} | |
render() { | |
const { id, coverImage } = this.props | |
const { isVisibleEnough, isLoaded } = this.state | |
return ( | |
<div className="album-cover-container" id={id} | |
style={{ backgroundImage: isLoaded ? `url(${coverImage})` : `url(${this.generanteBluredImage(coverImage)})` }}> | |
{isVisibleEnough && !isLoaded && | |
<img src={coverImage} onLoad={() => this.imageLoaded()} | |
style={{ visibility: 'hidden' }} height="250" alt="album cover"/> | |
} | |
</div> | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment