Skip to content

Instantly share code, notes, and snippets.

@imkarthikk
Forked from yocontra/LazyLoad.js
Created December 8, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imkarthikk/b24677e78f3057abbb55 to your computer and use it in GitHub Desktop.
Save imkarthikk/b24677e78f3057abbb55 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