MENU

优化 Google Adsense 广告代码,提升网站加载速度

September 28, 2023 • 已被 195 位童鞋围观过 • 教程文章

网速的加载速度是衡量访客体验和 SEO (搜索引擎优化)的关键要素之一,尽管我的网站早已挂上 Google Adsense 广告代码并在近期顺利收到广告费,但每次对网站进行例行维护时,发现加载了Google Adsense 广告代码后,网站加载速度会明显变慢,访客体验有待优化——文章、图片、 Google Adsense 广告同时加载,直到广告加载完毕,整个网页才能算全部加载完成。

经原因排查,主要有 Google Adsense 广告中的图片容量偏大、JavaScript 请求次数过多,尽管 Google Adsense 在国内有 CDN 镜像服务器,以及代码自带异步加载等功能,但 Google 官方努力只是杯水车薪,依旧无法有效解决广告代码加载速度较慢的问题。

优化 Google Adsense 广告代码,提升网站加载速度

解决办法:
仅需调用一次 Google Adsense 的 JavaScript 广告代码,避免重复性加载。同时,使用延迟加载技术(Lazy Loading)延迟加载并显示 Google Adsense 广告。

首次,在您的主题页脚 (footer.php),插入以下代码,请注意替换成您自己的 ID 。

<script>
    function downloadJSAtOnload() {
        var element = document.createElement("script");
        element.setAttribute("async", "");
        element.src = "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-您的ID";
        element.setAttribute("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;
    }
</script>

接着,将以下代码放在指定的广告位,如侧边栏。可根据实际情况适当修改,请注意替换成您自己的 ID 。

<ins class="adsbygoogle"
    style="display:block"
    data-ad-client="ca-pub-您的ID"
    data-ad-slot="您的ID"
    data-ad-format="auto"
    data-full-width-responsive="true">
</ins>
<script>(adsbygoogle = window.adsbygoogle || []).push({});</script>

赶紧试试吧,用我的方法后,Google Adsense 广告加载速度是否更快?!

Q&A: Google允许这么改么?会不会被惩罚?
AdSense 允许对广告代码进行精简,我们只是合并了相同的JS代码

#这一行JS 不能删除或者减少,他对应的是每个广告
 <script>(adsbygoogle = window.adsbygoogle || []).push({});</script>