在Vue中添加Google AdSense会遇到很多问题:
<script>
标签作者把所有的坑都走了一遍之后,整理成本文,方便读者。
当我们在Google AdSense中获取到广告位代码后,常见的广告位代码主要分为三部分:
script
标签引入https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-2626122653479680
类似这样的JS。(adsbygoogle = window.adsbygoogle || []).push({});
当我们需要在Vue中引入以上代码时,会遇到第一个问题:
[Vue warn]: Error compiling template:
Templates should only be responsible for mapping the state to the UI. Avoid placing tags with side-effects in your templates, such as <script>, as they will not be parsed.
主要原因就是,Vue Templates中是不允许再出现Script标签的。虽然我们可以通过type来规避这个报错:type="application/javascript"
,但这并不能彻底解决问题。
当你把script
标签写在Vue templates中时,因为Vue会根据数据的变化动态渲染页面,会导致多次运行该代码。具体到Google AdSense的广告位代码,就会报错:
message: "adsbygoogle.push() error: All ins elements in the DOM with class=adsbygoogle already have ads in them."
上面的报错主要是因为多次执行adsbygoogle.push()
,换句话说就是push()
函数的运行次数和<ins>
广告位的数量不匹配,根本原因就是Vue多次渲染模板,导致push()
函数多次运行造成的。
(adsbygoogle = window.adsbygoogle || []).push({});
启动脚本,不要直接放到Vue Templates中。可以自定义一个window全局函数,把改代码放入其中,然后在Vue的mounted
生命周期中调用。代码如下:定义js window全局函数:
window['addAds'] = function(){
let childList = document.getElementsByClassName('gads');
for (let i = 0; i < childList.length; i++) {
(adsbygoogle = window.adsbygoogle || []).push({});
}
}
重要提示:如果你的Google AdSense广告宽度、高度有问题,无法自适应广告位!请把上面的代码放到
window.onload=function(){}
中执行。具体可以参考文章:Google AdSense广告高度宽度错误、无法自适应的完美解决方案
Vue Templates中引入Google AdSense广告位:
<div class="gads">
<!-- 右侧边栏 -->
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-2626122653479680"
data-ad-slot="8640757447"
data-ad-format="auto"
data-full-width-responsive="true"></ins>
</div>
Vue Mounted中调用window全局函数,启动Google AdSense广告:
mounted() {
window.addAds();
}
大功告成!
本站的Google AdSense广告就是通过以上代码展示的,效果如下图: