|
1 | 1 | import React from 'react'; |
2 | 2 | import ReactDOM from 'react-dom'; |
3 | 3 | import { PropTypes } from 'prop-types'; |
| 4 | +import isIntersectionObserverAvailable from '../utils/intersection-observer'; |
4 | 5 |
|
5 | 6 | class PlaceholderWithoutTracking extends React.Component { |
6 | 7 | constructor(props) { |
7 | 8 | super(props); |
| 9 | + |
| 10 | + const supportsObserver = isIntersectionObserverAvailable(); |
| 11 | + |
| 12 | + this.LAZY_LOAD_OBSERVER = { supportsObserver }; |
| 13 | + |
| 14 | + if (supportsObserver) { |
| 15 | + const { threshold } = props; |
| 16 | + |
| 17 | + this.LAZY_LOAD_OBSERVER.observer = new IntersectionObserver( |
| 18 | + this.checkIntersections, { rootMargin: threshold + 'px' } |
| 19 | + ); |
| 20 | + } |
| 21 | + } |
| 22 | + |
| 23 | + checkIntersections(entries) { |
| 24 | + entries.forEach(entry => { |
| 25 | + if (entry.isIntersecting) { |
| 26 | + entry.target.onVisible(); |
| 27 | + } |
| 28 | + }); |
8 | 29 | } |
9 | 30 |
|
10 | 31 | componentDidMount() { |
11 | | - this.updateVisibility(); |
| 32 | + if (this.placeholder && |
| 33 | + this.LAZY_LOAD_OBSERVER && this.LAZY_LOAD_OBSERVER.observer) { |
| 34 | + this.placeholder.onVisible = this.props.onVisible; |
| 35 | + this.LAZY_LOAD_OBSERVER.observer.observe(this.placeholder); |
| 36 | + } |
| 37 | + |
| 38 | + if (this.LAZY_LOAD_OBSERVER && |
| 39 | + !this.LAZY_LOAD_OBSERVER.supportsObserver) { |
| 40 | + this.updateVisibility(); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + componentWillUnMount() { |
| 45 | + if (this.LAZY_LOAD_OBSERVER) { |
| 46 | + this.LAZY_LOAD_OBSERVER.observer.unobserve(this.placeholder); |
| 47 | + } |
12 | 48 | } |
13 | 49 |
|
14 | 50 | componentDidUpdate() { |
15 | | - this.updateVisibility(); |
| 51 | + if (this.LAZY_LOAD_OBSERVER && |
| 52 | + !this.LAZY_LOAD_OBSERVER.supportsObserver) { |
| 53 | + this.updateVisibility(); |
| 54 | + } |
16 | 55 | } |
17 | 56 |
|
18 | 57 | getPlaceholderBoundingBox(scrollPosition = this.props.scrollPosition) { |
@@ -77,14 +116,14 @@ class PlaceholderWithoutTracking extends React.Component { |
77 | 116 |
|
78 | 117 | PlaceholderWithoutTracking.propTypes = { |
79 | 118 | onVisible: PropTypes.func.isRequired, |
80 | | - scrollPosition: PropTypes.shape({ |
81 | | - x: PropTypes.number.isRequired, |
82 | | - y: PropTypes.number.isRequired, |
83 | | - }).isRequired, |
84 | 119 | className: PropTypes.string, |
85 | 120 | height: PropTypes.number, |
86 | 121 | placeholder: PropTypes.element, |
87 | 122 | threshold: PropTypes.number, |
| 123 | + scrollPosition: PropTypes.shape({ |
| 124 | + x: PropTypes.number.isRequired, |
| 125 | + y: PropTypes.number.isRequired, |
| 126 | + }), |
88 | 127 | width: PropTypes.number, |
89 | 128 | }; |
90 | 129 |
|
|
0 commit comments