Google AdSenseの広告ユニットにLazy Loadを設定する方法

パブリッシャーがしばしば直面する共通の問題は、Google AdSenseが私たちのオリジナルのブログの速度に影響を与えることです。リソースを最適化するためのコントロールを持っていないために、我々はちょうど悲しい感じになってしまう。

YouTubeの動画サムネイルと同じように、広告ユニットの画像にもWebPを使用する必要があります。皮肉なことに、彼らは時々、GZIP圧縮で提供したり、リソースを最小化しておくことに悩まされることはありません。膨大なリソースと多くのDNSルックアップの余分な負荷は、私たちのページ速度を地獄のように殺しています。

数ヶ月前、広告ユニットの速度問題についてツイートしたところ、満足のいく回答は得られませんでした。AdSenseがオリジナルコンテンツの読み込みを遅くするのを防ぐ解決策で、私自身は戻ってきました。

正直なところ、個人的には画像であっても遅延ロードはあまり好きではありません。しかし、それでも、私はちょうど軽量のオプションを共有したいと思います。もし、広告ユニットよりもプライマリーコンテンツを先に提供することに強いこだわりがあるのであれば、一度試してみてはいかがでしょうか。

AdSenseのレイジーローディングの設定方法について

当然ながら、オリジナルの広告ユニットコードはこのような形になります。

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

技術的な詳細。基本的に何が起こるか、それは非同期形式でロードすること、ブラウザはHTMLの解析をブロックせずにadsbygoogle.jsスクリプトをダウンロードし続けることを意味します。

しかし、ここでは、遅延ロード法では、私は本当のDEFERにASYNCメソッドを変更するつもりです。AdSenseスクリプトはブラウザでダウンロードを開始し、ウィンドウがメインウェブページの読み込みを完了した時点で初めてダウンロードされる。この方法では、訪問者はAdSenseのために迅速にページ全体を見るために待機する必要はありません。

この目的のために、あなたの広告ユニットで任意の大きな変更を行う必要はありません。単に我々はすべての魔法を行いますadsbygoogle.jsを読み込むのスタイルを変更します。

以下の2つのステップを踏むだけです。

既存のすべての広告ユニットから以下のスクリプトを削除します。

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

これで、次のように表示されます。

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

その後、以下のJavaScriptコードをテーマフッターのbodyタグの直前に追加してください。

方法1.オンロードイベント

ヒント:NoptimizeタグはAutoptimizeと互換性を持たせるために存在します。AdSenseのレイジーローダーのインライン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. 上記のコードは、カスタムスクリプトを追加するためにテーマオプションが利用可能であれば、それを介して使用することができます。
  2. Genesisの場合は、Genesis Simple Hooksプラグインでgenesis_afterオプションを指定して使用します。
  3. または他のテーマのHeader and Footerプラグインを使用します。
  4. GeneratePressのElements > hooksを使用することができます。
genesis hooks option

このスクリプトは具体的に何をするのですか?

このスクリプトは、メインページの読み込みが完了した後に、AdSense広告ユニットの読み込みを開始し、表示されるようにします。だから、Lazy Loading for Google AdSenseと名付けた。

方法2. onscrollイベント

この方法は、ユーザーがウェブページをスクロールしたときのみ広告ユニットをロードし、スクロールしないときは広告ユニットをロードしません。

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

方法3. ユーザーインタラクションに広告ユニットを表示する

収益やパフォーマンスを犠牲にすることなく、タイムリーに広告を表示したい場合は、ユーザーの操作に応じてJSをダウンロードし、実行するプラグイン「Flying Scripts by WP Speed Matters」を利用することが可能です。

一番良いのは、広告コードを全く変更する必要がないことです。

flying scripts plugin settings for lazy loading
フライングスクリプトのすっきりとしたUI
  • プラグインの設定から、adsbygoogleというキーワードを入れる。
  • その後、設定を保存し、ページキャッシュをパージ(消去)します。これで完了です。

業績結果

私はMediavine広告ネットワーク(これはアドセンス広告ユニットよりも重いされている)を使用している私のクライアントのサイトのいずれかでこのプラグインを使用してきました, コア不可欠は、モバイルとデスクトップの両方で正常に通過.

core vital result

以下の記事もご覧ください。

コメントする

「Google AdSenseの広告ユニットにLazy Loadを設定する方法」への129件のフィードバック

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

      返信
  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.

    返信
  2. That was an amazing article, your article gave me more clarity about ADSENSE. It was nice to read your article.

    返信
  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.

    返信
  4. “Method 2. onscroll event” makes my Web Vital Score go from 64 to 98 on mobile, thank you sooo much !

    返信
  5. 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

    返信
  6. 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?

    返信
  7. 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;

    返信
      • 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

        返信
  8. 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?

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

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

      返信
  10. 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.

    返信
  11. 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.. 🙂

    返信
  12. 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

    返信
  13. 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

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

    返信
  15. Thanks a lot, but this is not lazy loading. This is just deferring the loading.
    Definitely not the same thing…

    返信
  16. 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.

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

      返信
  17. 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?

    返信
      • 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?

        返信
  18. 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…

    返信
  19. Actually this is not lazy load, this is defer load, there is a different between lazy loading and defer loading.

    返信
  20. As I said in my post above, I do not use it because I believe it may affect revenue due to less ad impressions.

    返信
    • As I said in my post above, I do not use it because I believe it may affect revenue due to less ad impressions.

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

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

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

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

      返信
  23. 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 😉

    返信
  24. 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

    返信
  25. 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

    返信
  26. 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.

    返信
  27. 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.

    返信
  28. 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.

    返信
    • Thanks for the feedback.

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

      返信
    • Thanks for the feedback.

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

      返信
  29. 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.

    返信
  30. 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.

    返信
  31. Yes, this would be helpful for improving page load time. I’d like to know how this performs for you.
    Thanks

    返信
    • 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

      返信
  32. Really Awesome Bro. I will try this trick now on my website.

    Thanks for sharing the wonderful tips with us 🙂

    返信
    • Yes, this would be helpful for improving page load time. I’d like to know how this performs for you.
      Thanks

      返信