Как настроить ленивую загрузку для рекламных блоков Google AdSense

Одна из распространенных проблем, с которой часто сталкиваются издатели, заключается в том, что Google AdSense влияет на скорость работы нашего блога. Из-за отсутствия контроля над оптимизацией ресурсов мы просто впадаем в уныние.

Подобно миниатюрам видео на YouTube, они должны использовать WebP для изображений рекламных блоков. Иронично, что иногда они не утруждают себя обслуживанием со сжатием GZIP или минимизацией ресурсов. Массивные ресурсы и дополнительные нагрузки, связанные с многочисленными поисками DNS, убивают нашу скорость страницы.

Несколько месяцев назад, когда я написал в Твиттере о проблеме скорости рекламных блоков, я не получил никакого удовлетворительного ответа. Я вернулся с решением, которое не позволит AdSense замедлять загрузку вашего оригинального контента.

Честно говоря, лично я не являюсь большим поклонником ленивой загрузки даже для изображений. Но все же, я просто хочу поделиться легким вариантом. Если вам понравится, вы можете попробовать один раз, если вы очень заинтересованы в том, чтобы обслуживать сначала основной контент, а потом рекламные блоки.

Совет: Вы можете использовать Ezoic, чтобы зарабатывать больше, чем AdSense, и размещать WP бесплатно.

Инструкция по настройке ленивой загрузки для 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>

Технические детали: В основном происходит так, что он загружается в асинхронной форме, то есть браузер продолжает загрузку скрипта adsbygoogle.js, не блокируя разбор HTML.

Но здесь, в методе ленивой загрузки, я собираюсь заменить метод ASYNC на настоящий DEFER. Скрипт AdSense начнет загружаться в браузере, только когда окно завершит загрузку основной веб-страницы. Таким образом, посетителю не придется ждать, пока он быстро просмотрит всю страницу для AdSense.

Для этого вам не нужно вносить какие-либо значительные изменения в ваш рекламный блок. Просто мы изменим стиль загрузки adsbygoogle.js, который сделает все волшебство.

Все, что вам нужно сделать, это выполнить следующие два шага

Удалите приведенный ниже скрипт из всех существующих рекламных блоков.

<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. событие onload

Подсказка: Тег Noptimize присутствует для совместимости с Autoptimize. Он предотвращает агрегацию 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. Приведенный выше код вы можете использовать через опцию Theme, если она доступна для добавления пользовательского скрипта
  2. Для Genesis используйте плагин Genesis Simple Hooks с опцией genesis_after
  3. или плагин Header and Footer для любой другой темы.
genesis hooks option

Что именно делает этот скрипт?

Этот скрипт гарантирует, что ваш рекламный блок AdSense начнет загружаться и станет видимым после завершения полной загрузки вашей основной веб-страницы. Именно поэтому я назвал его «Ленивая загрузка для 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. Отображение рекламных блоков по взаимодействию с пользователем

Если вы хотите своевременно отображать рекламные объявления без ущерба для доходов и производительности, вы можете использовать плагин «Flying Scripts by WP Speed Matters» для загрузки и выполнения JS на основе взаимодействия с пользователем.

Самое приятное, что вам не нужно вносить никаких изменений в рекламный код.

flying scripts plugin settings for lazy loading
Аккуратный и чистый пользовательский интерфейс Flying Script
  • Перейдите в настройки плагина, включите ключевое слово adsbygoogle
  • Затем сохраните настройки и очистите (очистите) кэш страницы. Вот и все.

Результат работы

Я использовал этот плагин на сайте одного из моих клиентов, который использует рекламную сеть Mediavine (которая является более тяжелой, чем рекламные блоки Adsense), ядро успешно прошло для мобильных и настольных компьютеров.

core vital result

Вам также следует прочитать эти статьи

Оставьте комментарий

129 комментариев к “Как настроить ленивую загрузку для рекламных блоков Google AdSense”

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

    Ответить
  3. 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;

    Ответить
  4. 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.

    Ответить
  5. I tested both codes, the code that works as Lazyload pagespeed speed testindo outputs like 99%. https://www.havadurumu15gunluk.xyz/havadurumu/630/istanbul-hava-durumu-15-gunluk.html However, with the page late loading code, the pagespeed speed test is not very successful. I also doubt whether it is against the adsense rules. I am thinking of getting support via mail. https://havadurumu16gunluk.xyz/havadurumu/728/izmir-hava-durumu-16-gunluk.html

    Ответить
  6. 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

    Ответить
  7. 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.

    Ответить
  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?

    Ответить
  9. 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…

    Ответить
    • 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.

      Ответить
    • 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.

      Ответить
  10. 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.

    Ответить
  11. 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.

    Ответить
  12. 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.

    Ответить
  13. 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.

    Ответить
  14. 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.

    Ответить
    • 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

      Ответить