@@ -2,41 +2,23 @@ import React, { useEffect } from 'react';
22
33export default function Root ( { children } ) {
44 useEffect ( ( ) => {
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 ) ;
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 ) ;
3115 }
3216
3317 // 清理函数
3418 return ( ) => {
35- const ampAutoAds = document . querySelector ( 'amp-auto-ads' ) ;
3619 if ( ampAutoAds && ampAutoAds . parentNode ) {
3720 ampAutoAds . parentNode . removeChild ( ampAutoAds ) ;
3821 }
39- window . removeEventListener ( 'DOMContentLoaded' , insertAdsenseCode ) ;
4022 } ;
4123 } , [ ] ) ;
4224
0 commit comments