Skip to content

Instantly share code, notes, and snippets.

@franklinjavier
Forked from yocontra/LazyLoad.js
Created October 10, 2015 14:31
Show Gist options
  • Save franklinjavier/35bf5311fca1e5fc30be to your computer and use it in GitHub Desktop.
Save franklinjavier/35bf5311fca1e5fc30be to your computer and use it in GitHub Desktop.
lazy loading react components, useful for video/audio/etc
module.exports = function(el, distance) {
if (typeof distance !== 'number') {
distance = 0;
}
// TODO: use distance to create alternate bounding client rect
var rect = el.getBoundingClientRect();
var paddedRect = {
top: rect.top + distance,
left: rect.left + distance,
right: rect.right - distance,
bottom: rect.bottom - distance
};
var pageHeight = (window.innerHeight || document.documentElement.clientHeight);
var pageWidth = (window.innerWidth || document.documentElement.clientWidth);
var isOnPage = (paddedRect.top >= 0 && paddedRect.left >= 0);
var isUnderPage = (paddedRect.bottom <= pageHeight && paddedRect.right <= pageWidth);
return (isOnPage && isUnderPage);
};
var React = require('react');
var events = require('add-event-listener');
var isVisible = require('../isVisible');
var LazyLoad = React.createClass({
displayName: 'LazyLoad',
propTypes: {
distance: React.PropTypes.number,
component: React.PropTypes.node.isRequired,
children: React.PropTypes.node.isRequired
},
getDefaultProps: function() {
return {
distance: 100
};
},
getInitialState: function() {
return {
visible: false
};
},
componentDidMount: function() {
this._checkViewport();
events.addEventListener(window, 'scroll', this._checkViewport);
events.addEventListener(window, 'resize', this._checkViewport);
},
componentWillUnmount: function() {
events.removeEventListener(window, 'scroll', this._checkViewport);
events.removeEventListener(window, 'resize', this._checkViewport);
},
_checkViewport: function() {
if (!this.isMounted()) {
return;
}
var el = this.getDOMNode();
this.setState({
visible: isVisible(el, this.props.distance)
});
},
render: function() {
// when not visible, return our placeholder
if (!this.state.visible) {
return this.props.component;
}
// otherwise return the children
return this.props.children;
}
});
module.exports = LazyLoad;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment