[英]How do I add script dynamically and run it. I am able to add it to my html code, but it is not executed
我有一个博客(40 多篇文章) 在每篇文章中,都有一个 id="ad" 的 div 元素。
我想编写一个脚本,将在该 div 中添加(另一个)脚本,因此广告只会显示在 div 所在的位置。 我的广告提供商是adsterra
。
我想在我的目标元素(div 标签)中添加下面的代码。 此代码由我的广告提供商提供。
<script type="text/javascript">
atOptions = {
'key' : '648ed94d49e39704aa01f7',
'format' : 'iframe',
'height' : 90,
'width' : 728,
'params' : {}
};
document.write('<scr' + 'ipt type="text/javascript" src="http' + (location.protocol === 'https:' ? 's' : '') + '://botsane.cm/648ed9424ed890aeb17/invoke.js"></scr' + 'ipt>');
</script>
我已经完成了以下操作(不起作用)。
document.getElementById('ad').innerHTML = `(the code above with correct escapes)`;
我也尝试了以下代码,但它再次不起作用。
var div = document.getElementById('ad');
var ad = document.createElement('script');
ad.text = `
atOptions = {
'key' : '648ed94d49e39704aa01f7',
'format' : 'iframe',
'height' : 90,
'width' : 728,
'params' : {}
};
document.write('<scr' + 'ipt type="text/javascript" src="http' + (location.protocol === 'https:' ? 's' : '') + '://botsane.cm/648ed9424ed890aeb17/invoke.js"></scr' + 'ipt>');
`;
div.appendChild(ad);
document.write
不能用于来自异步脚本的拥有文档,并且注入的脚本始终是异步的。
(另外,是atOptions
还是adOptions
?)
document.querySelector('[id=ad]').insertAdjacentHTML('beforeend', `
<scr`+`ipt type="text/javascript">
atOptions = {
'key' : '648ed94d49e39704aa01f7',
'format' : 'iframe',
'height' : 90,
'width' : 728,
'params' : {}
};
<scr`+`ipt>
<scr`+`ipt type="text/javascript" src="http` + (location.protocol === 'https:' ? 's' : '') + `://botsane.cm/648ed9424ed890aeb17/invoke.js"></scr`+`ipt>`
);
我建议将script
标记留在页面末尾。 但是,解决方案可能如下:
const ad = document.getElementById('ad')
const script = document.createElement('script')
script.type = "text/javascript"
script.innerHTML = `
atOptions = {
'key' : '648ed94d49e39704aa01f7',
'format' : 'iframe',
'height' : 90,
'width' : 728,
'params' : {}
};
document.write('<scr' + 'ipt type="text/javascript" src="http' + (location.protocol === 'https:' ? 's' : '') + '://botsane.cm/648ed9424ed890aeb17/invoke.js"></scr' + 'ipt>');
`
ad.appendChild(script)
好的,我想做一些事情,这样我就不必编辑所有 40 多篇文章来添加广告代码。
我找不到动态插入脚本的方法。 有时广告会显示但不合适(而且看起来不太好)。
我删除了所有与广告相关的代码,只留下没有广告的代码博客应用程序。 然后我改变了看法,决定编辑主题。 我的网站由 Ghost 提供支持,并且我使用的是版本主题。 我下载了当前主题,并对其进行了编辑以在文章末尾显示广告。
现在,如果我更改广告提供商或其他任何情况,我将只需要在一个地方(在主题中)更新代码。
顺便说一句,我的网站是https://blog.nirmites.com
HTML5 不允许使用innerHTML
属性动态添加脚本标签,因此您的代码将不会执行! 相反,您可以使用appendChild
。
target.appendChild('your script tag');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.