子问题是相互关联的,因此为了清楚起见,我会将它们按顺序排列。
问题 - 1:使用 JavaScript 根据设备的浏览器/视口(viewport)宽度加载不同的 AdSense 广告尺寸/格式是个好主意吗?
我并不是在询问 Google AdSense 的 TOS 或其他政策是否合适。我已经照顾好他们了。
我想知道的是,使用 JavaScript 来执行此操作有什么缺点吗?我的意思是,这会影响 Adsense 提供的广告质量吗?或者没关系?
问题 - 2:有更好的方法吗?
(2a) 我找到了两个不同的代码片段来实现我的需要。我不知道哪个更可靠或更好。
This :
<script type="text/javascript"><!-- google_ad_client = "ca-pub-3658299045266116"; /* top */ if ($(window).width()<728 ){ google_ad_slot = "4414183254"; google_ad_width = 320; google_ad_height = 50; }else{ google_ad_slot = "1020377061"; google_ad_width = 728; google_ad_height = 90; } //--> </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
Someone says ,“你不能依赖窗口宽度,因为它不稳定。例如,在某些 Android 上你根本不能依赖它,因为浏览器需要最多 500 毫秒才能获得其宽度。”这是真的吗?应该引起关注吗?
(2b) 或 this :
<script type="text/javascript"> google_ad_client = "ca-publisher-id"; if (window.innerWidth >= 800) { google_ad_slot = "ad-unit-1"; google_ad_width = 728; google_ad_height = 60; } else if (window.innerWidth < 400) { google_ad_slot = "ad-unit-2"; google_ad_width = 300; google_ad_height = 250; } else { google_ad_slot = "ad-unit-3"; google_ad_width = 468; google_ad_height = 60; } </script> <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> </script>
再次,somebody else says , _“你的解决方案很棒,但可能会在旧版本的 IE 中出现问题。最好是使用 jQuery 查询浏览器宽度:
width = $(window).width();
” 但我可以'请勿出于 2(a) 代码片段中提到的原因使用它。
那么,什么是满足我需要的好方法呢? document.documentElement.clientWidth
?但是当页面在桌面或移动设备上缩放时,它的行为会怎样?
最佳答案
我们开始:
<script type="text/javascript">
var width = window.innerWidth || document.documentElement.clientWidth;
google_ad_client = "ca-publisher-id";
if (width >= 800) {
google_ad_slot = "ad-unit-1";
google_ad_width = 728;
google_ad_height = 60;
} else if ((width < 800) && (width < 400)) {
google_ad_slot = "ad-unit-2";
google_ad_width = 300;
google_ad_height = 250;
} else {
google_ad_slot = "ad-unit-3";
google_ad_width = 468;
google_ad_height = 60;
}
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
顺便说一句,这是“Google Adsense 团队批准的”方法。
来源: labnol.org
关于javascript - 使用 JavaScript 在不同设备上转换不同尺寸的广告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14673812/