@@ -2,23 +2,41 @@ import React, { useEffect } from 'react';
22
33export default function Root ( { children } ) {
44 useEffect ( ( ) => {
5- // 创建 AMP 自动广告元素
6- const ampAutoAds = document . createElement ( 'amp-auto-ads' ) ;
7- ampAutoAds . setAttribute ( 'type' , 'adsense' ) ;
8- ampAutoAds . setAttribute ( 'data-ad-client' , 'ca-pub-9617969692940509' ) ;
9-
10- // 将广告代码插入到 body 的开头
11- if ( document . body && document . body . firstChild ) {
12- document . body . insertBefore ( ampAutoAds , document . body . firstChild ) ;
13- } else if ( document . body ) {
14- document . body . appendChild ( ampAutoAds ) ;
5+ // 等待 DOM 完全加载后再插入广告代码
6+ const insertAdsenseCode = ( ) => {
7+ // 检查是否已经插入过广告代码
8+ if ( document . querySelector ( 'amp-auto-ads' ) ) {
9+ return ;
10+ }
11+
12+ // 创建 AMP 自动广告元素
13+ const ampAutoAds = document . createElement ( 'amp-auto-ads' ) ;
14+ ampAutoAds . setAttribute ( 'type' , 'adsense' ) ;
15+ ampAutoAds . setAttribute ( 'data-ad-client' , 'ca-pub-9617969692940509' ) ;
16+
17+ // 将广告代码插入到 body 的开头(紧跟在 <body> 标签后)
18+ if ( document . body && document . body . firstChild ) {
19+ document . body . insertBefore ( ampAutoAds , document . body . firstChild ) ;
20+ } else if ( document . body ) {
21+ document . body . appendChild ( ampAutoAds ) ;
22+ }
23+ } ;
24+
25+ // 如果 DOM 已经加载完成,直接插入
26+ if ( document . readyState === 'complete' || document . readyState === 'interactive' ) {
27+ insertAdsenseCode ( ) ;
28+ } else {
29+ // 否则等待 DOM 加载完成
30+ window . addEventListener ( 'DOMContentLoaded' , insertAdsenseCode ) ;
1531 }
1632
1733 // 清理函数
1834 return ( ) => {
35+ const ampAutoAds = document . querySelector ( 'amp-auto-ads' ) ;
1936 if ( ampAutoAds && ampAutoAds . parentNode ) {
2037 ampAutoAds . parentNode . removeChild ( ampAutoAds ) ;
2138 }
39+ window . removeEventListener ( 'DOMContentLoaded' , insertAdsenseCode ) ;
2240 } ;
2341 } , [ ] ) ;
2442
0 commit comments