Skip to content

Commit c6dba47

Browse files
committed
Use IntersectionObserver for guest ads
1 parent a472aba commit c6dba47

File tree

2 files changed

+47
-15
lines changed

2 files changed

+47
-15
lines changed

src/components/common/AdFeed.tsx

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,6 @@ function AdFeed({ forPost, index }: { forPost?: boolean; index: number }) {
3131
if (entry.isIntersecting && !initializedRef.current) {
3232
initializedRef.current = true;
3333
(window.adsbygoogle = window.adsbygoogle || []).push({});
34-
console.log('initialized!');
3534
}
3635
});
3736
},
@@ -41,6 +40,9 @@ function AdFeed({ forPost, index }: { forPost?: boolean; index: number }) {
4140
},
4241
);
4342
observer.observe(ref.current!);
43+
return () => {
44+
observer.disconnect();
45+
};
4446
}, [forPost]);
4547

4648
return (

src/containers/post/RelatedPostAd.tsx

Lines changed: 44 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,36 +1,66 @@
1-
import React, { useEffect } from 'react';
1+
import React, { useEffect, useRef } from 'react';
22
interface Props {
33
isMobile?: boolean;
44
}
55

66
function RelatedPostAd({ isMobile }: Props) {
7+
const initializedRef = useRef(false);
8+
const ref = useRef<HTMLDivElement>(null);
9+
710
useEffect(() => {
11+
if (!initializedRef.current) return;
812
try {
913
(window.adsbygoogle = window.adsbygoogle || []).push({});
1014
} catch (e) {}
1115
}, [isMobile]);
1216

17+
useEffect(() => {
18+
const observer = new IntersectionObserver(
19+
(entries) => {
20+
entries.forEach((entry) => {
21+
if (entry.isIntersecting && !initializedRef.current) {
22+
initializedRef.current = true;
23+
(window.adsbygoogle = window.adsbygoogle || []).push({});
24+
console.log('initialized!');
25+
}
26+
});
27+
},
28+
{
29+
rootMargin: '90px',
30+
threshold: 0,
31+
},
32+
);
33+
observer.observe(ref.current!);
34+
return () => {
35+
observer.disconnect();
36+
};
37+
}, []);
38+
1339
if (isMobile) {
1440
return (
41+
<div ref={ref}>
42+
<ins
43+
className="adsbygoogle"
44+
style={{ display: 'block' }}
45+
data-ad-format="fluid"
46+
data-ad-layout-key="-gh+5l+k-cu+l4"
47+
data-ad-client="ca-pub-5574866530496701"
48+
data-ad-slot="8237449336"
49+
/>
50+
</div>
51+
);
52+
}
53+
return (
54+
<div ref={ref}>
1555
<ins
1656
className="adsbygoogle"
1757
style={{ display: 'block' }}
1858
data-ad-format="fluid"
19-
data-ad-layout-key="-gh+5l+k-cu+l4"
59+
data-ad-layout-key="-7n+eu-z-1k+6t"
2060
data-ad-client="ca-pub-5574866530496701"
21-
data-ad-slot="8237449336"
61+
data-ad-slot="9497725960"
2262
/>
23-
);
24-
}
25-
return (
26-
<ins
27-
className="adsbygoogle"
28-
style={{ display: 'block' }}
29-
data-ad-format="fluid"
30-
data-ad-layout-key="-7n+eu-z-1k+6t"
31-
data-ad-client="ca-pub-5574866530496701"
32-
data-ad-slot="9497725960"
33-
/>
63+
</div>
3464
);
3565
}
3666

0 commit comments

Comments
 (0)