[Cocoon] Increase site loading speed by lazy loading Adsense

avatar
Share This:

Today I will show you how to lazy load Adsense to increase site loading speed. First, if you have auto ads turned on, turn them off from the Google Adsense page. After that, go to your own site and paste the following code in the ad code of the ad tab of Cocoon settings, so let’s change that.

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1234567890123456"
     crossorigin="anonymous"></script>
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-1234567890123456"
     data-ad-slot="1234567890"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>

Delete <script> to </script> from at the top of this and make it look like the following.

<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-1234567890123456"
     data-ad-slot="1234567890"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>

Save it.

Next, go to the access analysis/authentication tab in Cocoon settings, enter the following code in the footer code, and save.

<script>
//<![CDATA[
//lazy load ads
var lazyloadads = false;
window.addEventListener("scroll", function() {
    if ((document.documentElement.scrollTop != 0 && lazyloadads === false) || (document.body.scrollTop != 0 && lazyloadads === false)) {

        (function() {
            var ad = document.createElement('script');
            ad.type = 'text/javascript';
            ad.async = true;
            ad.src = 'https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js';
            var sc = document.getElementsByTagName('script')[0];
            sc.parentNode.insertBefore(ad, sc);
        })();

        lazyloadads = true;
    }
}, true)
//]]>
</script>

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

18 − 14 =