我正在尝试将外部JavaScript文件动态加载到HTML元素中以预览广告代码.脚本加载并执行但脚本包含"document.write",它有一个问题正确执行但没有错误.
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
source = 'http://ib.adnxs.com/ttj?id=555281';
// DOM Insert Approach
// -----------------------------------
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', source);
document.body.appendChild(script);
});
</script>
</head>
<body>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
如果,我可以让它工作
我没有能力修改脚本,因为它是由第三方生成和托管的.
有谁知道为什么document.write不能正常工作?有没有办法解决这个问题?
谢谢您的帮助!
另一个解决方案是创建一个iframe,然后在ajax调用准备就绪时在iframe中加载脚本:
var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
var doc = iframe.contentWindow.document;
// do this whenever you want (f.ex after ajax is made):
doc.open();
doc.write('<script src="http://ib.adnxs.com/ttj?id=555281">\x3C/script>');
doc.close();
Run Code Online (Sandbox Code Playgroud)
这样,document.write最终脚本不会影响您的网站,只会影响iframe.您需要设置iframe样式以适合广告.
你不想(当 dom 准备好时document.write)$(function()
取下document .ready包装纸。
并将您的移动到 - 之前</body>。(或容器位置 - 您希望小部件出现的位置。)
所以 :
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
</head>
<body>
//bla bla...
<script type="text/javascript">
(function (){
var source = 'http://ib.adnxs.com/ttj?id=555281';
// DOM Insert Approach
// -----------------------------------
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', source);
document.body.appendChild(script);
})();
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
重要的 :

| 归档时间: |
|
| 查看次数: |
7917 次 |
| 最近记录: |