Adsense广告错位与影响网站加载速度的解决方法

前些天给博客加入了Adsense广告,添加广告代码后整站速度都慢了,有时候甚至会出现图片都加载不出来的问题。而且有部分广告在本博客移动端的布局简直不堪入目! 其实只需要简单优化下广告代码就行了。让我们先看下默认的广告代码

Adsense广告代码

<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<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>

这就是我们获取到的默认的广告代码,下面看优化方法

优化

  • 解决广告错位

  • 我们只需要把代码中的data-full-width-responsive="true"改为data-full-width-responsive="false"即可

  • 防止影响网站加载速度

  • 同一页面插入多个广告,其中//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js这个js只需要引用一次即可
  • 修改JS的加载方法
<script>
window.onload = function() {
        setTimeout(function() {
                let script = document.createElement("script");
                script.setAttribute("data-ad-client", "ca-pub-你的id");
                script.setAttribute("async", "");
                script.src = "//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?";
                document.body.appendChild(script);
        }, 0);
};
</script>

这样改完后基本就看不出Adsense广告对网站加载速度的影响了!