After going through a lot of hurdles I managed to put on the ads.txt file, robots.txt and dynamic sitemap.xml to my site and they all work flawlessly.
A while back my website was approved by google AdSense for monetization, all I need to do was add a link tag and few scripts tags to my website head tag to get the ads showing. Adding links was very easy when using remix, the issue comes when I need to load external async scripts.
The script I need to add to my head is this:
<script
async
src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-xxxxxxxxxxxxxxx"
crossOrigin="anonymous"
></script>
When I check in the console, I see that my script has been added but the JavaScript has not executed. I am sure there are no issues with my google account and everything is fine there. It is just that ads are not showing in my website because the script is not loaded correctly.
Sometimes when I clear the cache and reload the website again, the ads appear only on the homepage for 1 second then disappear. This is the reason I think the script is not being loaded into my SSR app correctly.
I looked everywhere for the solution and even posted on remix github repo, no luck just yet. Out of all the solutions I found, here is what I tried:
dangerouslySetInnerHTML: Did not work
adding the script after mount using the useEffect (I mount the async script as it is after the setIsMounted is true): Did not work
using defer instead of async: Did not work
I solved this by removing the script from the head tag. Then I created a component that checks to see if the script is currently in the document head on location changes. If it is, then I push an ad. If not I add it first and then push an ad.
Here is some code.
const location = useLocation();
useEffect(() => {
handleAds();
}, [location.key]);
const handleAds = () => {
// check if script exists yet
if (!document.getElementById("adsbygoogleaftermount")) {
var script = document.createElement("script");
script.id = "adsbygoogleaftermount";
script.type = "text/javascript";
script.async = true;
script.src =
"https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js";
document.head.appendChild(script);
}
// push ad with every location change
window.adsbygoogle = window.adsbygoogle || [];
window.adsbygoogle.push({});
};
return (
<div className="mt-4">
<div key={location.key}> // <-- this is important
<ins
className="adsbygoogle"
style={{ display: "block" }}
data-ad-client="ca-pub-xxxxxxxxxxxxxxxx"
data-ad-slot="xxxxxxxxxx"
data-ad-format="auto"
data-full-width-responsive="true"
></ins>
</div>
)
}
This worked for placed ads as well as auto ads.