Jak skonfigurować Lazy Load dla jednostek reklamowych Google AdSense

Jednym z częstych problemów wydawców jest to, że Google AdSense wpływają na naszą oryginalną prędkość bloga. Ze względu na brak kontroli nad optymalizacją zasobów, kończymy po prostu smutno.

Podobnie jak w przypadku miniatur wideo z YouTube, powinni oni używać WebP dla obrazów jednostek reklamowych. To ironia, że czasami nie przejmują się serwowaniem z kompresją GZIP, lub utrzymują zasoby zminifikowane. Ogromne zasoby i dodatkowe obciążenia związane z wieloma DNS lookup, zabijają naszą prędkość strony jak diabli.

Kilka miesięcy temu, kiedy tweetowałem problem prędkości jednostek Ad, nie otrzymałem żadnej satysfakcjonującej odpowiedzi. Wracam sam z rozwiązaniem, które sprawi, że AdSense nie będzie spowalniać ładowania twoich oryginalnych treści.

Szczerze mówiąc, nie jestem osobiście wielkim fanem leniwego obciążenia nawet dla obrazów. Ale nadal chcę tylko podzielić się lekką opcją. Jeśli lubisz, możesz spróbować raz, jeśli jesteś bardzo zaniepokojony serwowaniem treści podstawowych najpierw, przed Ad Units.

Wskazówka: Możesz użyć Ezoic, aby zarobić więcej niż AdSense & host WP za darmo.

Instrukcja konfiguracji Lazy Loading dla AdSense

Oczywiście tak wygląda oryginalny kod jednostki reklamowej.

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

Szczegóły techniczne: Zasadniczo co się dzieje, że ładuje się on w formie asynchronicznej, czyli przeglądarka kontynuuje pobieranie skryptu adsbygoogle.js bez blokowania parsowania HTML.

Ale tutaj, w metodzie leniwego ładowania, zmienię metodę ASYNC na prawdziwą DEFER. Skrypt AdSense zacznie się pobierać w przeglądarce, dopiero gdy okno zakończy ładowanie głównej strony. W ten sposób odwiedzający nie musi czekać na szybkie obejrzenie całej strony dla AdSense.

W tym celu nie musisz wprowadzać żadnych dużych zmian w swojej jednostce reklamowej. Po prostu zmienimy styl ładowania adsbygoogle.js, który zrobi całą magię.

Wszystko, co musisz zrobić, to wykonać poniższe dwa kroki

Usuń poniższy skrypt z wszystkich istniejących jednostek reklamowych.

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

Teraz będzie to wyglądało tak

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

Następnie dodaj poniższy kod JavaScript w stopce motywu, możliwie tuż przed znacznikiem body.

Metoda 1. zdarzenie onload

Wskazówka: tag Noptimize jest obecny, aby uczynić go kompatybilnym z Autoptimize. Zapobiegnie to agregacji 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. Powyższy kod, możesz użyć poprzez opcję Theme jeśli jest dostępna dla dodania własnego skryptu
  2. Dla Genesis, użyj wtyczki Genesis Simple Hooks z opcją genesis_after
  3. lub wtyczka Header and Footer dla każdego innego motywu.
genesis hooks option

Co dokładnie robi ten skrypt?

Ten skrypt zapewni, że Twoja jednostka AdSense Ad zacznie się ładować i stanie się widoczna po zakończeniu pełnego ładowania głównej strony internetowej. Dlatego nazwałem go Lazy Loading for Google AdSense.

Metoda 2. Zdarzenie onscroll

Takie podejście spowoduje, że reklama będzie ładowana tylko wtedy, gdy użytkownik będzie przewijał stronę, a nie będzie tego robił.

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

Metoda 3. Wyświetlanie Ad Units na podstawie interakcji z użytkownikiem

Jeśli chcesz wyświetlać advt w odpowiednim czasie bez kompromisu dla przychodów i wydajności, możesz użyć „Flying Scripts by WP Speed Matters” plugin do pobierania i wykonywania JS na podstawie interakcji użytkownika.

Najlepsza część, nie musisz w ogóle wprowadzać żadnych zmian w swoim kodzie reklamowym.

flying scripts plugin settings for lazy loading
Schludny i czysty UI Flying Script
  • Przejdź do ustawień wtyczki, dołącz słowo kluczowe adsbygoogle
  • Następnie zapisz ustawienia i oczyść (wyczyść) cache strony. To wszystko.

Wynik wykonania

Używam tej wtyczki na jednej z moich stron klientów, która używa sieci reklamowej Mediavine (która jest bardziej ciężka niż jednostki Adsense Ad), rdzeń żywotny przeszedł pomyślnie dla Mobile i Desktop zarówno.

core vital result

Warto też przeczytać te artykuły

Dodaj komentarz

130 komentarzy do “Jak skonfigurować Lazy Load dla jednostek reklamowych Google AdSense”

  1. Hi! I use manually placed adsense ads in articles and also I use adsense vignette ads (auto). If I use your second code will it affect vignette ads? Because they are shown between pages and not on pages.

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

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

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

    Odpowiedz
  4. 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

    Odpowiedz
  5. 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?

    Odpowiedz
  6. 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;

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

        Odpowiedz
  7. what about the header tag which will be added for Adsense approval?

    this is present in the header, should we keep this or remove it?

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

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

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

    Odpowiedz
  10. 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.. 🙂

    Odpowiedz
  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

    Odpowiedz
  12. 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

    Odpowiedz
  13. The second method drastically increased my pagespeed score. Is there any issue with the second method when compared to the first?.

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

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

      Odpowiedz
  15. 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?

    Odpowiedz
      • I don’t the exact number of articles I have read. Finally Boom 💣
        Previously with ads my speed decrease by 50 points on the lighthouse
        Now my speed is above 97 even with ads

        One more question, My non-amp pages are faster than amp pages…which should I use for my blog posts?

        Odpowiedz
  16. 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…

    Odpowiedz
  17. Gulshan, I want to know, will this accept Google Adsense policy? Becuase they are very strict when comes to modification of their ad code.

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

      Odpowiedz
  18. Gulshan, I want to know, will this accept Google Adsense policy? Becuase they are very strict when comes to modification of their ad code.

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

      Odpowiedz
  19. 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 😉

    Odpowiedz
  20. Thanks really helpful will use it in my website..hope there is a similar guide for other ads as well nice website keep it up

    Odpowiedz
  21. Thanks really helpful will use it in my website..hope there is a similar guide for other ads as well nice website keep it up

    Odpowiedz
  22. 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.

    Odpowiedz
  23. 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.

    Odpowiedz
  24. 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.

    Odpowiedz
    • Thanks for the feedback.

      Lazy load is not harming anything of Google AdSense or their Advertiser, so it’s fair use in my opinion.

      Odpowiedz
    • Thanks for the feedback.

      Lazy load is not harming anything of Google AdSense or their Advertiser, so it’s fair use in my opinion.

      Odpowiedz
  25. 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.

    Odpowiedz
  26. 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.

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

      Odpowiedz