-
-
Save CYBAI/301b3ebbb71c02fb48c6 to your computer and use it in GitHub Desktop.
lazy loading react components, useful for video/audio/etc
This file contains 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
module.exports = (el, distance) => { | |
if (typeof distance !== 'number') { | |
distance = 0; | |
} | |
let rect = el.getBoundingClientRect(); | |
let paddedRect = { | |
top: rect.top + distance, | |
left: rect.left + distance, | |
right: rect.right - distance, | |
bottom: rect.bottom - distance | |
}; | |
let pageHeight = (window.innerHeight || document.documentElement.clientHeight); | |
let pageWidth = (window.innerWidth || document.documentElement.clientWidth); | |
let isOnPage = (paddedRect.top >= 0 && paddedRect.left >= 0); | |
let isUnderPage = (paddedRect.bottom <= pageHeight && paddedRect.right <= pageWidth); | |
return (isOnPage && isUnderPage); | |
}; |
This file contains 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 React from 'react'; | |
import ReactDOM from 'react-dom'; | |
import isVisible from './isVisible'; | |
class LazyLoad extends React.Components { | |
constructor() { | |
super(); | |
this.props = { | |
distance: 100 | |
}; | |
this.state = { | |
visible: false | |
}; | |
this._checkViewport = this._checkViewport.bind(this); | |
} | |
componentDidMount() { | |
this._checkViewport(); | |
window.addEventListener('scroll', this._checkViewport); | |
window.addEventListener('resize', this._checkViewport); | |
} | |
componentWillUnmount() { | |
window.removeEventListener('scroll', this._checkViewport); | |
window.removeEventListener('resize', this._checkViewport); | |
} | |
_checkViewport() { | |
if (!this.isMounted()) { | |
return; | |
} | |
let el = ReactDOM.findDOMNode(this); | |
this.setState({ | |
visible: isVisible(el, this.props.distance) | |
}); | |
} | |
render() { | |
// when not visible, return our placeholder | |
if (!this.state.visible) { | |
return this.props.component; | |
} | |
// otherwise return the children | |
return this.props.children; | |
} | |
} | |
LazyLoad.propTypes = { | |
distance: React.PropTypes.number, | |
component: React.PropTypes.node.isRequired, | |
children: React.PropTypes.node.isRequired | |
}; | |
module.exports = LazyLoad; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment