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

标签 javascript internet-explorer iframe cross-browser

背景:我需要在加载 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/

相关文章:

javascript - 铁路由器 waitOn Meteor.user()

javascript - 通过 JavaScript 将两个按钮添加到一个 div

javascript - 为什么这个 Javascript 在 IE 中不起作用

html - css 在 IE 9 中不起作用,但在 chrome 中运行良好

javascript - Bootstrap JS 选项卡中的定时选项卡切换

javascript - 处理 <select> 中的选择选项的事件是什么?

javascript - 在特定条件下手动调用事件处理程序时 IE 出错

javascript - React-router 和 iframe,浏览器历史记录

html - 如何隐藏 Youtube 控件但显示全屏按钮?

javascript - iframe 和 angularjs 的浏览器历史记录