gpt4 book ai didi

javascript - 如何以跨浏览器方式(特别是 IE!)在 iframe 中附加和执行脚本?

转载 作者:行者123 更新时间:2023-11-29 15:53:05 25 4
gpt4 key购买 nike

背景:我需要在加载 DOM 后加载广告脚本。因为许多脚本使用 document.write() 和其他潜在的错误函数在 DOM 加载后运行,所以我想在 iframe 中加载脚本。

因此,当需要显示广告时,会触发执行以下操作的事件:

        var iframe = document.createElement('iframe');
iframe.setAttribute('id', 'iframeId');
iframe.setAttribute('src', 'about:blank');

var adContainer = document.getElementById('AdContainer');
adContainer.appendChild(iframe);

var val = '<html><head></head><body>';
val += '<scr' + 'ipt type="text/javascript" src="' + url + '"></scr' + 'ipt>';
val += '</body></html>';

如果我不将 html 和 body 标签分配给 val,脚本会自动附加到 iframe 的头部,并且无法在 FF 中执行。在 IE 中,脚本不会在有或没有 head/body/html 标签的情况下执行。

        var doc = iframe.contentWindow || iframe.contentDocument;

if (doc.document){
doc = doc.document
}

doc.open();
doc.write(val);
doc.close();

我在这里找到了最后一段代码:Why does appending a <script> to a dynamically created <iframe> seem to run the script in the parent page? .我不想在 iframe 中加载 jquery,我只想附加一个脚本并让它执行。

我目前的解决方案似乎在 FF 和 Webkit 中运行良好。但是,IE 不执行该脚本。脚本已写入页面,但并未开始运行。有没有更好的方法将脚本附加到 iframe 以便它跨浏览器运行?或者是否可以告诉 IE 运行脚本?

我知道我可以通过 iframe 加载带有广告脚本的外部文档,但如果我可以动态执行此操作,我不想额外调用我的服务器。此外,我尝试在 iframe 的主体上使用 appendChild() 来插入脚本,但是由于脚本元素是在 iframe 的 DOM 之外创建的,所以这似乎不起作用。

最佳答案

当 IE 应该动态执行时,IE 需要在脚本标签中加入 defer="true"

关于javascript - 如何以跨浏览器方式(特别是 IE!)在 iframe 中附加和执行脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3049466/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com