在我个人看来,谷歌广告是各大广告商中体验最好的一个,因为他的广告比较智能,不会出现一些不堪入目的广告,同时它的自动广告我也觉得很满意,当然,最重要的一点就是:在众多广告联盟中,只有谷歌通过了我的申请!!!

速度优化

自从我的小站接入谷歌广告以来,它偶尔的加载缓慢,甚至一些资源根本无法正常加载,导致了网页不能正常滚动,这已经非常严重的影响了访问的体验!!!

谷歌广告虽好,但是也要进行优化一下,就在历史性的今天,我把它给解决掉了。不多说,直接开始。

分析

首先分析一下谷歌给我们的代码:

//引用的主要js
<script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
//右侧栏的一块广告位代码
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-xxxxxxxxxxx"
     data-ad-slot="xxxxxxxx"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>

其实谷歌已经做过了优化,使用的是async异步请求加载的方式,但是,国内的情况大家都有了解,所以会有偶尔加载失败的情况。

JS监听加载

这里我使用了JS监听加载的方式,来使网站看起来加载非常快

只需要修改这段代码

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

修改为:

<script>
window.onload = function() {
        setTimeout(function() {
                let script = document.createElement("script");
                script.setAttribute("async", "");
                script.src = "//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js";
                document.body.appendChild(script);
        }, 2e3);
}
</script>

原理

这个的原理就是我们在网站加载完成,且那个浏览器标签上的圆圈不转的时候,才开始加载谷歌的JS,并不是真正意义的加速,只不过让广告在后台加载了,这样的话不会影响到页面的访问。

建议

当然,如果你有很多个广告位,并不需要每个代码位都加载这个JS文件,只需要在页脚加载一次即可。

完整js代码

<script>
window.onload = function() {
        setTimeout(function() {
                let script = document.createElement("script");
                script.setAttribute("async", "");
                script.src = "//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js";
                document.body.appendChild(script);
        }, 2e3);
}
</script>
<!-- 文章页脚广告位 -->
<ins class="adsbygoogle"
     style="display:block"
     data-ad-client="ca-pub-9646939170017511"
     data-ad-slot="8136524364"
     data-ad-format="auto"
     data-full-width-responsive="true"></ins>
<script>
     (adsbygoogle = window.adsbygoogle || []).push({});
</script>

注意中间的data-ad-clientdata-ad-slot改成自己的。

文章转载自:风也の小站

最后修改:2020 年 04 月 19 日
如果觉得我的文章对你有用,请随意赞赏