Skip to content

Instantly share code, notes, and snippets.

@CYBAI
Forked from yocontra/LazyLoad.js
Last active November 12, 2015 04:39
Show Gist options
  • Save CYBAI/301b3ebbb71c02fb48c6 to your computer and use it in GitHub Desktop.
Save CYBAI/301b3ebbb71c02fb48c6 to your computer and use it in GitHub Desktop.
lazy loading react components, useful for video/audio/etc
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);
};
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