![]() |
Image: Lazy Load AdSense |
To set up lazy loading for AdSense ad units, you will need to follow these steps:
First, make sure that you have the latest version of the AdSense code on your website. You can find the latest code by going to your AdSense account and selecting the ad unit you want to modify.
Next, you will need to add the following code to the head of your HTML file, just before the closing
</head>
tag:
<script>
window.lazyLoadOptions = {
elements_selector: ".adsense"
};
</script>
This code tells the lazy loading script which elements on the page to apply lazy loading to. In this case, we are targeting elements with the class .adsense
, so any AdSense ad units that have this class will be lazy loaded.
- Now you will need to add the lazy loading script to your website. You can do this by adding the following code to the head of your HTML file, just before the closing
</head>
tag:
<script src="https://cdnjs.cloudflare.com/ajax/libs/lazysizes/5.2.2/lazysizes.min.js" async></script>
This script is provided by the LazySizes library, which is a popular lazy loading library that is widely used and well-supported.
- Finally, you will need to modify your AdSense ad units to include the
.adsense
class. You can do this by adding the following code to your AdSense ad unit:
<ins class="adsense" style="display:block" data-ad-client="ca-pub-1234567890" data-ad-slot="1234567890" data-ad-format="auto"></ins>
Make sure to replace ca-pub-1234567890
and 1234567890
with your own AdSense publisher ID and ad unit ID.
That's it! With these steps, your AdSense ad units should now be lazy loaded, which means that they will only be loaded when they are needed, rather than all at once when the page first loads. This can help improve the performance of your website and provide a better user experience for your visitors.