Como configurar o carregamento lento para blocos de anúncios do Google AdSense

Um problema comum que os editores enfrentam frequentemente é que o Google AdSense afecta a velocidade original do nosso blogue. Devido a não termos controlo sobre a optimização de recursos, acabamos por nos sentir tristes.

Tal como as miniaturas de vídeos do YouTube, deveriam estar a utilizar WebP para imagens de unidades de publicidade. É irónico, que por vezes não se preocupem em servir com compressão GZIP, ou manter os recursos minificados. Os recursos massivos e a carga extra de muitas pesquisas DNS, matam a velocidade da nossa página como o inferno.

Há alguns meses atrás, quando tweetei o problema da velocidade da unidade de anúncio, não obtive qualquer resposta satisfatória. Eu próprio voltei com uma solução que impedirá o AdSense de atrasar o carregamento do seu conteúdo original.

Honestamente, não sou pessoalmente um grande fã da carga preguiçosa, mesmo para imagens. Mas mesmo assim, só quero partilhar uma opção leve. Se quiser, pode tentar uma vez se estiver altamente preocupado em servir primeiro o conteúdo primário, antes das Unidades de Anúncio.

Dica: Pode usar Ezoic para ganhar mais do que AdSense & WP anfitrião sem custos.

Instruções para configurar o carregamento lento para o AdSense

Naturalmente, é este o aspecto de um código de unidade de anúncio original.

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- leaderboard -->
<ins class="adsbygoogle"
 style="display:inline-block;width:728px;height:90px"
 data-ad-client="ca-pub-xxxxxxxxxxxxxxxx"
 data-ad-slot="1234567890"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>

Detalhes técnicos: Basicamente o que acontece que carrega em forma assíncrona, significa que o browser continua a descarregar o script adsbygoogle.js sem bloquear a análise HTML.

Mas aqui, no método de carregamento preguiçoso, vou mudar o método ASYNC para o verdadeiro DEFER. O script AdSense começará a descarregar no browser, apenas uma vez a janela completará o carregamento da página web principal. Desta forma, o visitante não tem de esperar por ver a página inteira rapidamente para o AdSense.

Para este efeito, não precisa de fazer grandes mudanças na sua unidade de anúncios. Simplesmente alteraremos o estilo de carregamento adsbygoogle.js que irá fazer toda a magia.

Tudo o que precisa de seguir abaixo dois Passos

Remover abaixo o guião de todas as unidades de publicidade existentes.

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

Agora vai aparecer assim

<ins class="adsbygoogle"
 style="display:inline-block;width:728px;height:90px"
 data-ad-client="ca-pub-xxxxxxxxxxxxxxxx"
 data-ad-slot="1234567890"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>

Depois disso, adicione abaixo o código JavaScript no seu Rodapé Temático, possivelmente um pouco antes da etiqueta do corpo.

Método 1. evento onload

Dica: A etiqueta Noptimize está presente para tornar compatível com a Autoptimize. Evitará a agregação do carregador preguiçoso AdSense em linha JS.

<!--noptimize-->
<script type="text/javascript">
function downloadJSAtOnload() {
var element = document.createElement("script");
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>
<!--/noptimize-->
  1. Acima do código, pode utilizar através da opção Tema, se disponível, para adicionar script personalizado
  2. Para Génesis, faça uso através do plugin Genesis Simple Hooks com opção genesis_after
  3. ou Header and Footer plugin para qualquer outro tema.
genesis hooks option

O que é que este guião faz exactamente?

Este guião assegurará que a sua unidade de anúncios do AdSense começará a carregar e se tornará visível após terminar o carregamento completo da sua página web principal. É por isso que lhe dei o nome, Lazy Loading para Google AdSense.

Método 2. evento onscroll

Esta abordagem só carregará a unidade de anúncio quando o utilizador percorrer a página web, caso contrário não o fará.

<script type='text/javascript'>
//<![CDATA[
var la=!1;window.addEventListener("scroll",function(){(0!=document.documentElement.scrollTop&&!1===la||0!=document.body.scrollTop&&!1===la)&&(!function(){var e=document.createElement("script");e.type="text/javascript",e.async=!0,e.src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js";var a=document.getElementsByTagName("script")[0];a.parentNode.insertBefore(e,a)}(),la=!0)},!0);
//]]>
</script>

Método 3. Mostrar unidades de anúncio sobre a interacção do utilizador

Se quiser exibir o aviso em tempo útil sem comprometer as receitas e o desempenho, pode usar o plugin “Flying Scripts by WP Speed Matters” para descarregar e executar o JS com base na interacção do utilizador.

A melhor parte, não precisa de fazer quaisquer alterações no seu código de anúncio.

flying scripts plugin settings for lazy loading
A limpa e limpa IU do Flying Script
  • Ir para configurações de plugin, incluir a palavra-chave adsbygoogle
  • Depois, guardar as definições e limpar (limpar) a cache da página. É isso mesmo.

Resultado do desempenho

Tenho utilizado este plugin num dos sites dos meus clientes que utiliza a rede de anúncios Mediavine (que está a ser mais pesada do que as unidades de anúncios Adsense) o núcleo vital passou com sucesso para Mobile e Desktop ambos.

core vital result

Também deve ler estes artigos

WordPress List - Subscription Form
Quer mais?
Imagine receber Tutoriais todos os dias! Isso é FELICITATÓRIO. Subscreva agora.

Deixe um comentário

129 comentários em “Como configurar o carregamento lento para blocos de anúncios do Google AdSense”

    • Great Now My site works really awesome fast. i am also like to know How to do Https for my website using cloudfare ? Can you guide me.

      One more doubt : How to use cloudfare ssl for normal html websites ?

      Thank you

      Responder
  1. Fabulous! 245 ms load time. How cloudflare is caching HTML content? Part of their paid plan?
    “cf-cache-status” shows HIT, which I never get for any HTML content. I always get very long wait time with CF, around 0.5 to 1 Sec every time.

    On the server side, using Key-CDN cache enabler, and Autoptimize, there’s only Two CSS and one JS file, excluding adsense scripts.

    Responder
  2. Fabulous! 245 ms load time. How cloudflare is caching HTML content? Part of their paid plan?
    “cf-cache-status” shows HIT, which I never get for any HTML content. I always get very long wait time with CF, around 0.5 to 1 Sec every time.

    On the server side, using Key-CDN cache enabler, and Autoptimize, there’s only Two CSS and one JS file, excluding adsense scripts.

    Responder
  3. Just Now I removed the lazy load Adsense option on my website,

    Once you add the script for lazy load, site loading is very fast, but the main problem is if your having more than 3 ads means sometimes ads not showing, it shows blank space, once refresh only ads came, I recently found out this problem.

    Then only i remove the script, normally my side load time is 5 secs, while using lazy load 2 secs only.

    Responder
  4. Great share Gulshan. Personally, I’m not a big fan of Google AdSense and prefer to stay away since it slows down the website and distracts the users.

    I don’t want my readers to click on the ad and leave my site while reading an article where I could have gotten a chance to make an affiliate sale. Also, Google pays peanuts, which is another sad truth.

    Lazy load can reduce the server load and improve the site speed by a good margin. Thanks for sharing the script.

    Responder
  5. Great share Gulshan. Personally, I’m not a big fan of Google AdSense and prefer to stay away since it slows down the website and distracts the users.

    I don’t want my readers to click on the ad and leave my site while reading an article where I could have gotten a chance to make an affiliate sale. Also, Google pays peanuts, which is another sad truth.

    Lazy load can reduce the server load and improve the site speed by a good margin. Thanks for sharing the script.

    Responder
  6. You must execute for every ad after load the script:

    (adsbygoogle = window.adsbygoogle || []).push({});

    so if you have 3 ads you must execute this code 3 times 😉

    Responder
    • Hi,
      Great question!

      We are not modifying heavily like modifications. We are just adjusting same script in a way to load after finishing page load. From async to defer. So, I don’t think it’s a violation.

      Responder
    • Hi,
      Great question!

      We are not modifying heavily like modifications. We are just adjusting same script in a way to load after finishing page load. From async to defer. So, I don’t think it’s a violation.

      Responder
  7. Hi, I just wanted to implement your code but then I wasn’t able to see your code, already tried opening it in Chrome and Firefox but where the code is supposed to be there is just a grey box unfortunately…

    Responder
  8. Based on this “Update 12/09/2017: I have removed this method from my blog since I found that it reduces Ad impressions. So, please implement at your own responsibility.”

    Can anyone confirm if this method still affects impressions?

    Responder
  9. Gulshan,

    Which of the both methods are you seeing an effective balance between load speed and the revenue?

    In the comments you said, you haven’t using the lazy load.

    Can we able to add an array tags to the JS code, so that it applies to only that ads code? We can easily add a comment to the adsense code if they are below the fold.

    That should help in even fine tune the code.

    Responder
    • At the moment of writing this comment, I am using second method which is based on scroll. I feel, it is subject to test what perform best for each site.

      Responder
  10. Hey buddy! I just come across your article and this is literally amazing but I had one issue.. I m trying to work with the second option, which is the scroll event, I did the steps u said on the first event but besides putting the lazy load code I put the scroll one but it doesn’t work, PLEASE I was looking for this script for months and finally when I found it, it won’t work could you please show me exactly how it works or is there any video I can follow..

    Really appreciate you effort

    Responder
  11. My site’s speed was seriously battered due to adsense codes but using this code raised my speed to 90. Thanks for this hint, its really the drug for FCP and CLS

    Responder
  12. Gracias hermano por el aporte este truco de lazy espectacular me ayudo en Lighthouse Report Viewer de 40 a 80 puntos….todo debido a ese script de google adsense.. 🙂

    Responder
  13. Thanks so much for the code and your research Gulshan. My Pagespeed score is now, as you say, as without Adsense placed on the page. Also reassuring that you’ve been using the second option since June 2020, I’m guessing without Google Adsense wrath. Thanks also for your continued watch of this post. With Core Web Vitals being slapped on us in a couple of months, I’m sure many people are looking for this type of assistance now.

    Responder
    • You do not need to put this script in all Ad units. As provided code will work across all web page if once added in body tag.

      Responder
  14. Brother, initially it worked fine but after 1 day it stoped working and my ads load very fast, page speed decreased. Please help

    Responder
      • Hey Gulshan, thanks for providing us with this code. But I discovered that it’s not lazy loading, but just to defer loading of ads.

        I will like it if you will make it to load ads only when user scrolls to the viewport where the ads are meant to show.

        Thanks a lot

        Responder
  15. Improved JS version as per new AdSense code. Added query string for publishing ID and crossOrigin property.

    function downloadJSAtOnload() {
    var element = document.createElement(“script”);
    element.src = “https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-1234567890″;
    element.crossOrigin=”anonymous”;
    document.body.appendChild(element);
    }
    if (window.addEventListener)
    window.addEventListener(“load”, downloadJSAtOnload, false);
    else if (window.attachEvent)
    window.attachEvent(“onload”, downloadJSAtOnload);
    else window.onload = downloadJSAtOnload;

    Responder
  16. Thanks for the great tip. However, recently AdSense launched new ad code that looks like this:

    Do we need to update the Javascript you provided?

    Responder
  17. Theoretically speaking, does lazy loading affect ads targeting? I kinda notice that the ads I see when lazy loading seem quite different from AdSense auto ads.

    Thank you

    Responder
  18. Method 2 worked for me, but method 1 did not.
    Method 2 increases pagespeed from a meager 50 to a whopping 92 on mobile.
    Method 1 did nothing.
    The downside is that method 2 loads the add only after a scroll, even if it is above the fold.

    I find it amazing that google puts so much emphasis on pagespeed while at the same time slows sites with adsense down to impossible levels.

    Responder
  19. Hello. Thank you so much for the useful information.

    I have read all the posts and comments.

    Google Adsense updated, but this code still works fine for me.

    But as you said in your comment, “If you have AdSense placement mainly in above the fold, you should avoid.” Due to the problem, I also stopped using it.

    By any chance, how are you displaying AdSense now?

    Are you just using the default (provided by Google) code?

    Or

    Can you please let me know if you are using another method?

    Thank you.

    Responder
    • 1. There is one customized responsive ad unit added in top header using Elements > Hook option. Here’s the code if you need.

      2. Then I have two responsive ad units added after paragraphs 2 and 8 using Ad Inserter. That’s all.

      Responder