Skip to content

Instantly share code, notes, and snippets.

@dazld
Last active July 28, 2016 06:28
Show Gist options
  • Save dazld/e60cc6897bea11da4b5600947187bc57 to your computer and use it in GitHub Desktop.
Save dazld/e60cc6897bea11da4b5600947187bc57 to your computer and use it in GitHub Desktop.

el.getBoundingClientRect()

http://output.jsbin.com/rasaso

desktop: 1000 ops = 3-5ms mobile: 1000 ops = 30ms (busts 60fps limit)

1,000,000 ops = 1573ms (desktop) 17000+ms (mobile)

ie should put a warning about calling this too much on mobile, but it's pretty solid for desktop.

import React, { PropTypes, Component } from 'react';
import debounce from '../lib/debounce';
import cx from 'classnames';
class OnVisible extends Component {
constructor() {
super(...arguments);
this.onScroll = debounce(this.onScroll.bind(this), 10);
this.state = {
visible: false,
bottom: 0,
top: 0
};
}
componentDidMount() {
this.onScroll();
window.addEventListener('scroll', this.onScroll);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.onScroll);
}
onScroll() {
const pos = window.scrollY + window.innerHeight;
const box = this.refs.holder.getBoundingClientRect();
const top = box.top + (box.height / 2) + (window.pageYOffset || document.documentElement.scrollTop) - (document.documentElement.clientTop || 0);
const isVisible = top < pos;
this.setState({
visible: this.state.visible || isVisible,
top
});
}
render() {
const { visible } = this.state;
const classes = cx(this.props.className, {
visible
});
return (
<div
className={classes}
ref="holder">
{this.props.children}
</div>
);
}
}
OnVisible.propTypes = {
className: PropTypes.string,
children: PropTypes.node
};
export default OnVisible;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment