我不敢相信这有多难找到,但即使在谷歌开发者文档中我也找不到它。我需要能够动态地,only使用 JavaScript 插入 adsense。我也在 StackOverflow 上查看过,其他一些人也问过这个问题,但没有回复。希望这将是一个更好的解释并能得到一些答复。
基本上,用户插入我的脚本,我们称之为my.js
(目前还不能说具体是什么。)my.js
已加载并在my.js
一些嵌入媒体显示在他们的页面上,然后我需要以某种方式附加生成的 HTML:
<script type="text/javascript"><!--
google_ad_client = "ca-pub-xxx";
/* my.js example Ad */
google_ad_slot = "yyy";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
里面有一个特定的<div>
(或其他)元素。有任何想法吗?
附:没有像 jQuery 这样的库,我无法将 HTML 插入到页面上,除非它通过 JavaScript 并且必须插入到特定的位置<div>
我命名(我正在使用Sizzle http://sizzlejs.com对于我的 JS 库(如果有帮助的话)
其他答案提出的用于异步加载 AdSense 脚本的简单技术将不起作用,因为 Google 使用document.write()
AdSense 脚本内部。document.write()
仅在页面创建期间有效,当异步加载的脚本执行时,页面创建已经完成。
为了使这个工作,你需要覆盖document.write()
因此,当 AdSense 脚本调用它时,您可以自己操作 DOM。这是一个例子:
<script>
window.google_ad_client = "123456789";
window.google_ad_slot = "123456789";
window.google_ad_width = 200;
window.google_ad_height = 200;
// container is where you want the ad to be inserted
var container = document.getElementById('ad_container');
var w = document.write;
document.write = function (content) {
container.innerHTML = content;
document.write = w;
};
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://pagead2.googlesyndication.com/pagead/show_ads.js';
document.body.appendChild(script);
</script>
该示例首先缓存本机document.write()
函数在局部变量中。然后它会覆盖document.write()
在它的内部,它使用innerHTML
注入 Google 将发送到的 HTML 内容document.write()
。完成后,它会恢复本机document.write()
功能。
这项技术是从这里借用的:http://blog.figmentengine.com/2011/08/google-ads-async-asynchronous.html http://blog.figmentengine.com/2011/08/google-ads-async-asynchronous.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)