Delay Loading Google Auto Ads

Recently I found that the Google auto ads significantly slows down the page loading speed. There are also many discussions about this. As a static website, fast loading speed is crutial. In this post, we will optimize the PageSpeed Insights score by delay loading auto ads.

First, let's check the current PSI score in mobile: PSI Mobile

It seems that the Reduce unused JavaScript section has many items to be improved. Check the official Google auto ads script:

<script data-ad-client="ca-pub-000xxx" async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

Although the script is async, the page loading speed is affected. Changing async to defer makes no difference: https://stackoverflow.com/questions/10808109/script-tag-async-defer

Loading Ads after Page Loaded

Refer to: # How to Setup Lazy Load for Google AdSense Ad units?

Wrap the ads loading into a function and load ads after page onload event is triggered:

<script>
   function func() {
   ...
   }
   if (window.addEventListener)
       window.addEventListener("load", func, false);
   else if (window.attachEvent)
       window.attachEvent("onload", func);
   else window.onload = func;
</script>

Then the original script is rewritten like this:

<script type="text/javascript">
    function downloadJsAtOnload() {
        var element = document.createElement("script");
        element.setAttribute("data-ad-client", "ca-pub-000xxx");
        element.async = true;
        element.src = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js";
        document.body.appendChild(element);
    };
    if (window.addEventListener)
        window.addEventListener("load", downloadJsAtOnload, false);
    else if (window.attachEvent)
        window.attachEvent("onload", downloadJsAtOnload);
    else window.onload = downloadJsAtOnload;
</script>

Unfortunately, the above script still not works. The PSI score is still very poor ( < 50).

Delay Loading Auto Ads

Let's do it a little bit aggresive, loading the ads after 5s by setTimeout():

<script>
   setTimeout(function(){
       ...
   }, 5000);
</script>

The final implementation (remember to replace data-ad-client to your own id):

<script type="text/javascript">
    function downloadJsAtOnload() {
        setTimeout(function downloadJs() {
            var element = document.createElement("script");
            element.setAttribute("data-ad-client", "ca-pub-000xxx");
            element.async = true;
            element.src = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js";
            document.body.appendChild(element);
        }, 5000);
    };
    if (window.addEventListener)
        window.addEventListener("load", downloadJsAtOnload, false);
    else if (window.attachEvent)
        window.attachEvent("onload", downloadJsAtOnload);
    else window.onload = downloadJsAtOnload;
</script>

Now it works!

PSI Mobile