If you want to load AdSense ads only when they are visible in the Viewport, read further. Without modifying the Ad code, we are lazy loading the advertisement only when the users scrolls to it and is visible on the user’s screen.
For example, if you place an Ad in the footer, when the user opens up your site, the Ad wont be loaded initially. When the user reaches your site’s footer, the Ad will be then loaded utilizing the lazyhtml.js script.
First add the below script to your sites header. I assume, you have already added the second line (if already running on AdSense). If already added, make sure you include the first line in the below code along with it. Refer our article on Adding AdSense Codes to WordPress.
<script async src="https://cdn.jsdelivr.net/npm/[email protected]/dist/lazyhtml.min.js" crossorigin="anonymous"></script>
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-xxxxxxxxxxxxxxxxxxxx" crossorigin="anonymous"></script>
Once lazyhtml js script is added to the sites header, you will now wrap any AdSense ad code with the ‘lazyhtml’ class. That’s it. Your Ad will be now lazily loaded. To confirm, Inspect the page, go to Network and refresh. Start scrolling. You will see, ad codes will only load when visible in the viewport (screen).
Refer the below ad code example which is already wrapped under the lazyhtml class. ‘onvisble‘ implies, script will be loaded when visible in user’s viewport.
<div class="lazyhtml" data-lazyhtml onvisible>
<script type="text/lazyhtml">
<!--
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-xxxxxxxxxxxxxxxxxxxxx"
data-ad-slot="YYYY"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
-->
</script>
</div>
This code isn’t limited to Ads. You can lazyload anything. Just wrap it under the lazyhtml class.
Thanks to the Open Source LazyHTML Java Script Library which made this possible. The LazyHTML JS loads through CDN and is extremely fast.
Note: We are not making any changes to the Ad codes, complying to the AdSense policies.
Tip: First, copy the above code as is in the Custom HTML Block where you want to show ads. Don’t Save. Create an Ad through AdSense. Copy only the contents inside the <ins and /ins> tags. Replace and Save.
Source: GitHub & stackoverflow