Improve ad display logic and integrate ads into more pages
Refactor AdSenseAd component to use ResizeObserver for more reliable initialization and add the component to FolxStadlPage, GeschichteLiedPage, and GipfelstammtischPage. Replit-Commit-Author: Agent Replit-Commit-Session-Id: 45a1dcfc-f8a2-475a-a6b9-96fbb841dc27 Replit-Commit-Checkpoint-Type: full_checkpoint Replit-Commit-Screenshot-Url: https://storage.googleapis.com/screenshot-production-us-central1/60d372ff-2c10-46c7-b01b-10c3435136b0/45a1dcfc-f8a2-475a-a6b9-96fbb841dc27/fmm3fpm
This commit is contained in:
@@ -1,4 +1,4 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
|
||||
interface AdSenseAdProps {
|
||||
adSlot: string;
|
||||
@@ -16,18 +16,51 @@ export default function AdSenseAd({
|
||||
className = ''
|
||||
}: AdSenseAdProps) {
|
||||
const adRef = useRef<HTMLDivElement>(null);
|
||||
const [isInitialized, setIsInitialized] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
try {
|
||||
// Ensure adsbygoogle is loaded
|
||||
if (typeof window !== 'undefined') {
|
||||
// @ts-ignore
|
||||
(window.adsbygoogle = window.adsbygoogle || []).push({});
|
||||
if (isInitialized) return;
|
||||
|
||||
const initializeAd = () => {
|
||||
const insElement = adRef.current?.querySelector('ins');
|
||||
if (!insElement) return;
|
||||
|
||||
// Check if element has width > 0
|
||||
const clientWidth = insElement.clientWidth;
|
||||
if (clientWidth > 0) {
|
||||
try {
|
||||
// @ts-ignore
|
||||
(window.adsbygoogle = window.adsbygoogle || []).push({});
|
||||
setIsInitialized(true);
|
||||
} catch (error) {
|
||||
console.error('AdSense initialization error:', error);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('AdSense initialization error:', error);
|
||||
};
|
||||
|
||||
// Try immediate initialization after short delay
|
||||
const timer = setTimeout(initializeAd, 100);
|
||||
|
||||
// Use ResizeObserver as fallback
|
||||
if (typeof window !== 'undefined' && window.ResizeObserver) {
|
||||
const observer = new ResizeObserver(() => {
|
||||
if (!isInitialized) {
|
||||
initializeAd();
|
||||
}
|
||||
});
|
||||
|
||||
if (adRef.current) {
|
||||
observer.observe(adRef.current);
|
||||
}
|
||||
|
||||
return () => {
|
||||
clearTimeout(timer);
|
||||
observer.disconnect();
|
||||
};
|
||||
}
|
||||
}, [adSlot]);
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}, [adSlot, isInitialized]);
|
||||
|
||||
const adStyle: React.CSSProperties = {
|
||||
display: 'block',
|
||||
@@ -44,7 +77,11 @@ export default function AdSenseAd({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`adsense-wrapper ${className}`} ref={adRef}>
|
||||
<div
|
||||
className={`adsense-wrapper w-full ${className}`}
|
||||
ref={adRef}
|
||||
style={{ width: '100%', minWidth: '320px' }}
|
||||
>
|
||||
<ins
|
||||
className="adsbygoogle"
|
||||
style={adStyle}
|
||||
|
||||
Reference in New Issue
Block a user