Come impostare il caricamento pigro per le unità pubblicitarie di Google AdSense

Un problema comune che gli editori devono spesso affrontare è che Google AdSense influisce sulla velocità del nostro blog originale. Non avendo il controllo sull’ottimizzazione delle risorse, finiamo per sentirci tristi.

Come le miniature dei video di YouTube, dovrebbero utilizzare WebP per le immagini delle unità pubblicitarie. È ironico che a volte non si preoccupino di servire con la compressione GZIP o di mantenere le risorse minificate. Le enormi risorse e i carichi extra di molte ricerche DNS uccidono la velocità della pagina.

Qualche mese fa, quando ho twittato il problema della velocità delle unità pubblicitarie, non ho ricevuto alcuna risposta soddisfacente. Sono tornato con una soluzione che impedirà ad AdSense di rallentare il caricamento dei contenuti originali.

Onestamente, personalmente non sono un grande fan del caricamento pigro anche per le immagini. Tuttavia, voglio condividere un’opzione leggera. Se vi piace, potete provarla una volta se siete fortemente interessati a servire prima i contenuti primari, prima delle unità pubblicitarie.

Suggerimento: è possibile utilizzare Ezoic per guadagnare più di AdSense e ospitare WP gratuitamente.

Istruzioni per l’impostazione del caricamento pigro per AdSense

Naturalmente, questo è l’aspetto del codice di un’unità pubblicitaria originale.

<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>

Dettagli tecnici: In pratica, il caricamento avviene in forma asincrona, ovvero il browser continua a scaricare lo script adsbygoogle.js senza bloccare l’analisi dell’HTML.

Ma qui, nel metodo di caricamento pigro, cambierò il metodo ASYNC in un vero e proprio DEFER. Lo script di AdSense inizierà a essere scaricato nel browser solo quando la finestra avrà completato il caricamento della pagina web principale. In questo modo, il visitatore non dovrà aspettare di vedere rapidamente l’intera pagina per vedere AdSense.

A questo scopo, non è necessario apportare grandi modifiche alla vostra unità pubblicitaria. Basterà modificare lo stile di caricamento di adsbygoogle.js che farà tutta la magia.

È sufficiente seguire i due passaggi seguenti

Rimuovere lo script sottostante da tutte le unità pubblicitarie esistenti.

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

Ora apparirà come segue

<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>

Successivamente, aggiungere il seguente codice JavaScript nel piè di pagina del tema, possibilmente prima del tag body.

Metodo 1. evento onload

Suggerimento: il tag Noptimize è presente per renderlo compatibile con Autoptimize. Impedisce l’aggregazione di AdSense lazy loader inline 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. Il codice precedente può essere utilizzato tramite l’opzione Tema, se disponibile, per aggiungere uno script personalizzato.
  2. Per Genesis, utilizzare il plugin Genesis Simple Hooks con l’opzione genesis_after
  3. o il plugin Header and Footer per qualsiasi altro tema.
genesis hooks option

Cosa fa esattamente questo script?

Questo script farà in modo che la vostra unità pubblicitaria AdSense inizi a caricarsi e diventi visibile dopo aver completato il caricamento della vostra pagina web principale. Ecco perché l’ho chiamato “Caricamento pigro per Google AdSense”.

Metodo 2. evento onscroll

Questo approccio carica l’unità pubblicitaria solo quando l’utente scorre la pagina web, altrimenti non la carica.

<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>

Metodo 3. Visualizzazione delle unità pubblicitarie in base all’interazione con l’utente

Se si desidera visualizzare gli annunci in modo tempestivo senza compromettere le entrate e le prestazioni, è possibile utilizzare il plugin “Flying Scripts by WP Speed Matters” per scaricare ed eseguire JS in base all’interazione dell’utente.

La cosa migliore è che non è necessario apportare alcuna modifica al codice degli annunci.

flying scripts plugin settings for lazy loading
L’interfaccia utente pulita e ordinata di Flying Script
  • Andare nelle impostazioni del plugin, includere la parola chiave adsbygoogle
  • Quindi, salvare le impostazioni e cancellare la cache della pagina. Questo è tutto.

Risultato delle prestazioni

Ho utilizzato questo plugin su un sito di un mio cliente che utilizza la rete pubblicitaria Mediavine (che è più pesante delle unità pubblicitarie Adsense) e il nucleo vitale è stato superato con successo sia per il mobile che per il desktop.

core vital result

Si consiglia di leggere anche questi articoli

Lascia un commento

129 commenti su “Come impostare il caricamento pigro per le unità pubblicitarie di Google AdSense”

    • 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.

      Rispondi
  1. 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.

    Rispondi
  2. 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.

    Rispondi
  3. 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

    Rispondi
  4. 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?

    Rispondi
  5. 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;

    Rispondi
      • 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

        Rispondi
  6. 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.

    Rispondi
  7. 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.. 🙂

    Rispondi
  8. 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

    Rispondi
  9. 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

    Rispondi
  10. 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.

    Rispondi
    • 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.

      Rispondi
  11. 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?

    Rispondi
  12. 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…

    Rispondi
    • 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.

      Rispondi
    • 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.

      Rispondi
  13. 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 😉

    Rispondi
  14. 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.

    Rispondi
  15. 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.

    Rispondi
  16. 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.

    Rispondi
  17. 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.

    Rispondi
  18. 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.

    Rispondi
    • 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

      Rispondi