Skip to content

Use IntersectionObserver when it's available #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Dec 30, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@
"padded-blocks": [1, "never"],
"quote-props": [1, "as-needed"],
"quotes": [1, 'single'],
"require-jsdoc": 1,
"require-jsdoc": 0,
"semi-spacing": 1,
"semi": 1,
"sort-keys": 0,
Expand Down
3 changes: 2 additions & 1 deletion src/components/LazyLoadComponent.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { PropTypes } from 'prop-types';

import PlaceholderWithoutTracking from './PlaceholderWithoutTracking.jsx';
import PlaceholderWithTracking from './PlaceholderWithTracking.jsx';
import isIntersectionObserverAvailable from '../utils/intersection-observer';

class LazyLoadComponent extends React.Component {
constructor(props) {
Expand Down Expand Up @@ -47,7 +48,7 @@ class LazyLoadComponent extends React.Component {
const { className, height, placeholder, scrollPosition, style,
threshold, width } = this.props;

if (this.isScrollTracked) {
if (this.isScrollTracked || isIntersectionObserverAvailable()) {
return (
<PlaceholderWithoutTracking
className={className}
Expand Down
38 changes: 38 additions & 0 deletions src/components/LazyLoadComponent.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ import Adapter from 'enzyme-adapter-react-16';
import LazyLoadComponent from './LazyLoadComponent.jsx';
import PlaceholderWithTracking from './PlaceholderWithTracking.jsx';
import PlaceholderWithoutTracking from './PlaceholderWithoutTracking.jsx';
import isIntersectionObserverAvailable from '../utils/intersection-observer';

jest.mock('../utils/intersection-observer');

configure({ adapter: new Adapter() });

Expand All @@ -16,6 +19,16 @@ const {
} = ReactTestUtils;

describe('LazyLoadComponent', function() {
const windowIntersectionObserver = window.IntersectionObserver;

beforeEach(() => {
isIntersectionObserverAvailable.mockImplementation(() => false);
});

afterEach(() => {
window.IntersectionObserver = windowIntersectionObserver;
});

it('renders a PlaceholderWithTracking when scrollPosition is undefined', function() {
const lazyLoadComponent = mount(
<LazyLoadComponent
Expand All @@ -30,6 +43,28 @@ describe('LazyLoadComponent', function() {
expect(placeholderWithTracking.length).toEqual(1);
});

it('renders a PlaceholderWithoutTracking when scrollPosition is undefined but IntersectionObserver is available', function() {
isIntersectionObserverAvailable.mockImplementation(() => true);
window.IntersectionObserver = jest.fn(function() {
this.observe = jest.fn(); // eslint-disable-line babel/no-invalid-this
});

const lazyLoadComponent = mount(
<LazyLoadComponent
style={{ marginTop: 100000 }}>
<p>Lorem Ipsum</p>
</LazyLoadComponent>
);

const placeholderWithTracking = scryRenderedComponentsWithType(
lazyLoadComponent.instance(), PlaceholderWithTracking);
const placeholderWithoutTracking = scryRenderedComponentsWithType(
lazyLoadComponent.instance(), PlaceholderWithoutTracking);

expect(placeholderWithTracking.length).toEqual(0);
expect(placeholderWithoutTracking.length).toEqual(1);
});

it('renders a PlaceholderWithoutTracking when scrollPosition is defined', function() {
const lazyLoadComponent = mount(
<LazyLoadComponent
Expand All @@ -39,9 +74,12 @@ describe('LazyLoadComponent', function() {
</LazyLoadComponent>
);

const placeholderWithTracking = scryRenderedComponentsWithType(
lazyLoadComponent.instance(), PlaceholderWithTracking);
const placeholderWithoutTracking = scryRenderedComponentsWithType(
lazyLoadComponent.instance(), PlaceholderWithoutTracking);

expect(placeholderWithTracking.length).toEqual(0);
expect(placeholderWithoutTracking.length).toEqual(1);
});

Expand Down
51 changes: 45 additions & 6 deletions src/components/PlaceholderWithoutTracking.jsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,57 @@
import React from 'react';
import ReactDOM from 'react-dom';
import { PropTypes } from 'prop-types';
import isIntersectionObserverAvailable from '../utils/intersection-observer';

class PlaceholderWithoutTracking extends React.Component {
constructor(props) {
super(props);

const supportsObserver = isIntersectionObserverAvailable();

this.LAZY_LOAD_OBSERVER = { supportsObserver };

if (supportsObserver) {
const { threshold } = props;

this.LAZY_LOAD_OBSERVER.observer = new IntersectionObserver(
this.checkIntersections, { rootMargin: threshold + 'px' }
);
}
}

checkIntersections(entries) {
entries.forEach(entry => {
if (entry.isIntersecting) {
entry.target.onVisible();
}
});
}

componentDidMount() {
this.updateVisibility();
if (this.placeholder &&
this.LAZY_LOAD_OBSERVER && this.LAZY_LOAD_OBSERVER.observer) {
this.placeholder.onVisible = this.props.onVisible;
this.LAZY_LOAD_OBSERVER.observer.observe(this.placeholder);
}

if (this.LAZY_LOAD_OBSERVER &&
!this.LAZY_LOAD_OBSERVER.supportsObserver) {
this.updateVisibility();
}
}

componentWillUnMount() {
if (this.LAZY_LOAD_OBSERVER) {
this.LAZY_LOAD_OBSERVER.observer.unobserve(this.placeholder);
}
}

componentDidUpdate() {
this.updateVisibility();
if (this.LAZY_LOAD_OBSERVER &&
!this.LAZY_LOAD_OBSERVER.supportsObserver) {
this.updateVisibility();
}
}

getPlaceholderBoundingBox(scrollPosition = this.props.scrollPosition) {
Expand Down Expand Up @@ -77,14 +116,14 @@ class PlaceholderWithoutTracking extends React.Component {

PlaceholderWithoutTracking.propTypes = {
onVisible: PropTypes.func.isRequired,
scrollPosition: PropTypes.shape({
x: PropTypes.number.isRequired,
y: PropTypes.number.isRequired,
}).isRequired,
className: PropTypes.string,
height: PropTypes.number,
placeholder: PropTypes.element,
threshold: PropTypes.number,
scrollPosition: PropTypes.shape({
x: PropTypes.number.isRequired,
y: PropTypes.number.isRequired,
}),
width: PropTypes.number,
};

Expand Down
26 changes: 26 additions & 0 deletions src/components/PlaceholderWithoutTracking.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,9 @@ import { configure, mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';

import PlaceholderWithoutTracking from './PlaceholderWithoutTracking.jsx';
import isIntersectionObserverAvailable from '../utils/intersection-observer';

jest.mock('../utils/intersection-observer');

configure({ adapter: new Adapter() });

Expand Down Expand Up @@ -73,6 +76,16 @@ describe('PlaceholderWithoutTracking', function() {
expect(placeholderWrapper.length).toEqual(numberOfPlaceholderWrappers);
}

const windowIntersectionObserver = window.IntersectionObserver;

beforeEach(() => {
isIntersectionObserverAvailable.mockImplementation(() => false);
});

afterEach(() => {
window.IntersectionObserver = windowIntersectionObserver;
});

it('renders the default placeholder when it\'s not in the viewport', function() {
const className = 'placeholder-wrapper';
const component = renderPlaceholderWithoutTracking({
Expand Down Expand Up @@ -168,4 +181,17 @@ describe('PlaceholderWithoutTracking', function() {

expect(onVisible).toHaveBeenCalledTimes(1);
});

it('doesn\'t track placeholder visibility if IntersectionObserver is available', function() {
isIntersectionObserverAvailable.mockImplementation(() => true);
window.IntersectionObserver = jest.fn(function() {
this.observe = jest.fn(); // eslint-disable-line babel/no-invalid-this
});
const onVisible = jest.fn();
const component = renderPlaceholderWithoutTracking({
onVisible,
});

expect(onVisible).toHaveBeenCalledTimes(0);
});
});
16 changes: 13 additions & 3 deletions src/hoc/trackWindowScroll.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,17 @@ import React from 'react';
import { PropTypes } from 'prop-types';
import debounce from 'lodash.debounce';
import throttle from 'lodash.throttle';
import isIntersectionObserverAvailable from '../utils/intersection-observer';

const trackWindowScroll = (BaseComponent) => {
class ScrollAwareComponent extends React.Component {
constructor(props) {
super(props);

if (isIntersectionObserverAvailable()) {
return;
}

const onChangeScroll = this.onChangeScroll.bind(this);

if (props.delayMethod === 'debounce') {
Expand All @@ -31,22 +36,25 @@ const trackWindowScroll = (BaseComponent) => {
}

componentDidMount() {
if (typeof window == 'undefined') {
if (typeof window == 'undefined' || isIntersectionObserverAvailable()) {
return;
}
window.addEventListener('scroll', this.delayedScroll);
window.addEventListener('resize', this.delayedScroll);
}

componentWillUnmount() {
if (typeof window === 'undefined') {
if (typeof window == 'undefined' || isIntersectionObserverAvailable()) {
return;
}
window.removeEventListener('scroll', this.delayedScroll);
window.removeEventListener('resize', this.delayedScroll);
}

onChangeScroll() {
if (isIntersectionObserverAvailable()) {
return;
}
this.setState({
scrollPosition: {
x: (typeof window == 'undefined' ?
Expand All @@ -63,10 +71,12 @@ const trackWindowScroll = (BaseComponent) => {

render() {
const { delayMethod, delayTime, ...props } = this.props;
const scrollPosition = isIntersectionObserverAvailable() ?
null : this.state.scrollPosition;

return (
<BaseComponent
scrollPosition={this.state.scrollPosition}
scrollPosition={scrollPosition}
{...props} />
);
}
Expand Down
6 changes: 6 additions & 0 deletions src/utils/intersection-observer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export default function() {
return (
'IntersectionObserver' in window &&
'isIntersecting' in window.IntersectionObserverEntry.prototype
);
}
24 changes: 24 additions & 0 deletions src/utils/intersection-observer.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import isIntersectionObserverAvailable from './intersection-observer';

describe('isIntersectionObserverAvailable', function() {
it('returns true if IntersectionObserver is available', function() {
window.IntersectionObserver = {};
window.IntersectionObserverEntry = {
prototype: {
isIntersecting: () => null,
},
};

expect(isIntersectionObserverAvailable()).toBe(true);
});

it('returns false if IntersectionObserver is not available', function() {
delete window.IntersectionObserver;
window.IntersectionObserverEntry = {
prototype: {},
};
delete window.IntersectionObserverEntry;

expect(isIntersectionObserverAvailable()).toBe(false);
});
});