@@ -92,28 +92,61 @@ const googleAdsenseClientId = import.meta.env.PUBLIC_GOOGLE_ADSENSE_CLIENT_ID;
9292 if (targetParagraph && targetParagraph.parentNode) {
9393 const adContainer = document .createElement (' div' );
9494 adContainer .className = ' my-6 flex justify-center ad-container' ;
95- adContainer .innerHTML = `
96- <div class="w-full max-w-sm">
97- <ins class="adsbygoogle"
98- style="display:block"
99- data-ad-client="${googleAdsenseClientId }"
100- data-ad-slot="2308296961"
101- data-ad-format="auto"
102- data-full-width-responsive="true"></ins>
103- <script>(adsbygoogle = window.adsbygoogle || []).push({});<\/ script>
104- </div>
105- ` ;
95+
96+ // Create ad wrapper
97+ const adWrapper = document .createElement (' div' );
98+ adWrapper .className = ' w-full' ;
99+
100+ // Create ins element
101+ const insElement = document .createElement (' ins' );
102+ insElement .className = ' adsbygoogle' ;
103+ insElement .style .display = ' block' ;
104+ insElement .setAttribute (' data-ad-client' , googleAdsenseClientId );
105+ insElement .setAttribute (' data-ad-slot' , ' 1673926045' );
106+ insElement .setAttribute (' data-ad-format' , ' auto' );
107+ insElement .setAttribute (' data-full-width-responsive' , ' true' );
108+
109+ // Create push script
110+ const pushScript = document .createElement (' script' );
111+ pushScript .textContent = ' (adsbygoogle = window.adsbygoogle || []).push({});' ;
112+
113+ // Append elements
114+ adWrapper .appendChild (insElement );
115+ adWrapper .appendChild (pushScript );
116+ adContainer .appendChild (adWrapper );
106117
107118 targetParagraph .parentNode .insertBefore (adContainer , targetParagraph .nextSibling );
108119 }
109120 });
110121 }
111122
112- // Run ad injection after content is loaded
113- if (document .readyState === ' loading' ) {
114- document .addEventListener (' DOMContentLoaded' , injectAdsIntoContent );
115- } else {
116- injectAdsIntoContent();
123+ // Function to wait for AdSense to load
124+ function waitForAdSense (callback , maxAttempts = 50 ) {
125+ let attempts = 0 ;
126+ const checkAdSense = () => {
127+ attempts ++ ;
128+ if (window .adsbygoogle ) {
129+ callback ();
130+ } else if (attempts < maxAttempts ) {
131+ setTimeout (checkAdSense , 100 ); // Check every 100ms
132+ } else {
133+ console .warn (' AdSense failed to load within timeout' );
134+ }
135+ };
136+ checkAdSense();
117137 }
138+
139+ // Run ad injection after both DOM and AdSense are loaded
140+ function initAds () {
141+ if (document.readyState === ' loading' ) {
142+ document .addEventListener (' DOMContentLoaded' , () => {
143+ waitForAdSense (injectAdsIntoContent );
144+ });
145+ } else {
146+ waitForAdSense(injectAdsIntoContent );
147+ }
148+ }
149+
150+ initAds ();
118151 </script >
119152)}
0 commit comments