@@ -3,64 +3,61 @@ import ReactDOM from 'react-dom';
3
3
import { PropTypes } from 'prop-types' ;
4
4
import isIntersectionObserverAvailable from '../utils/intersection-observer' ;
5
5
6
+ const checkIntersections = entries => {
7
+ entries . forEach ( entry => {
8
+ if ( entry . isIntersecting ) {
9
+ entry . target . onVisible ( ) ;
10
+ }
11
+ } ) ;
12
+ } ;
13
+
14
+ const LAZY_LOAD_OBSERVERS = { } ;
15
+
16
+ const getObserver = threshold => {
17
+ LAZY_LOAD_OBSERVERS [ threshold ] =
18
+ LAZY_LOAD_OBSERVERS [ threshold ] ||
19
+ new IntersectionObserver ( checkIntersections , {
20
+ rootMargin : threshold + 'px' ,
21
+ } ) ;
22
+
23
+ return LAZY_LOAD_OBSERVERS [ threshold ] ;
24
+ } ;
25
+
6
26
class PlaceholderWithoutTracking extends React . Component {
7
27
constructor ( props ) {
8
28
super ( props ) ;
9
29
10
- const supportsObserver =
30
+ this . supportsObserver =
11
31
! props . scrollPosition &&
12
32
props . useIntersectionObserver &&
13
33
isIntersectionObserverAvailable ( ) ;
14
34
15
- this . LAZY_LOAD_OBSERVER = { supportsObserver } ;
16
-
17
- if ( supportsObserver ) {
35
+ if ( this . supportsObserver ) {
18
36
const { threshold } = props ;
19
37
20
- this . LAZY_LOAD_OBSERVER . observer = new IntersectionObserver (
21
- this . checkIntersections ,
22
- { rootMargin : threshold + 'px' }
23
- ) ;
38
+ this . observer = getObserver ( threshold ) ;
24
39
}
25
40
}
26
41
27
- checkIntersections ( entries ) {
28
- entries . forEach ( entry => {
29
- if ( entry . isIntersecting ) {
30
- entry . target . onVisible ( ) ;
31
- }
32
- } ) ;
33
- }
34
-
35
42
componentDidMount ( ) {
36
- if (
37
- this . placeholder &&
38
- this . LAZY_LOAD_OBSERVER &&
39
- this . LAZY_LOAD_OBSERVER . observer
40
- ) {
43
+ if ( this . placeholder && this . observer ) {
41
44
this . placeholder . onVisible = this . props . onVisible ;
42
- this . LAZY_LOAD_OBSERVER . observer . observe ( this . placeholder ) ;
45
+ this . observer . observe ( this . placeholder ) ;
43
46
}
44
47
45
- if (
46
- this . LAZY_LOAD_OBSERVER &&
47
- ! this . LAZY_LOAD_OBSERVER . supportsObserver
48
- ) {
48
+ if ( ! this . supportsObserver ) {
49
49
this . updateVisibility ( ) ;
50
50
}
51
51
}
52
52
53
53
componentWillUnmount ( ) {
54
- if ( this . LAZY_LOAD_OBSERVER && this . LAZY_LOAD_OBSERVER . observer ) {
55
- this . LAZY_LOAD_OBSERVER . observer . unobserve ( this . placeholder ) ;
54
+ if ( this . observer ) {
55
+ this . observer . unobserve ( this . placeholder ) ;
56
56
}
57
57
}
58
58
59
59
componentDidUpdate ( ) {
60
- if (
61
- this . LAZY_LOAD_OBSERVER &&
62
- ! this . LAZY_LOAD_OBSERVER . supportsObserver
63
- ) {
60
+ if ( ! this . supportsObserver ) {
64
61
this . updateVisibility ( ) ;
65
62
}
66
63
}
0 commit comments