我有一个iframe通过javascript加载一些javascript。仅在Internet Explorer中,当且仅当IE具有javascript的缓存副本时,此方法才有效。这意味着重新加载页面(或以其他方式触发脚本再次运行,如果它被卡在函数或其他任何东西中)将导致此代码工作,否则它将不会。特别是,document.write调用无法发生。
主页:
<iframe height = "200" width = "200" id = "happy">
</iframe>
<script type="text/javascript">
var a = document.getElementById("happy");
scripttxt = '<a href="#" id="joy">JOY</a><'+'script type="text/javascript" src="fail.js"></'+'script>';
a.src = "about:blank";
a.contentWindow.document.open();
a.contentWindow.document.write("<h3>Preview:</h3>" + scripttxt + "");
a.contentWindow.document.close();
</script>
fail.js:
document.write(document.getElementById("joy"));
我意识到我可以使用条件注释让IE在主页的脚本中跳过document.open()
和document.close()
,但让IE跳过document.open()和document.close()会感觉有点hacky(编辑)... 并打破IE中的其他内容。
编辑:
当它正常工作时,iframe将在预览标题下包含文本:JOYhttp://mymachine:myport/mainpage.htm#
,其中JOY是超链接。失败时,将省略http://mymachine:myport/mainpage.htm#
。我实际上并不关心document.write如何处理a
节点的编写,只是它能够成功获取元素并成功编写内容。
我也按照贾斯汀的建议尝试了这个版本的脚本,但它的行为完全一样:
var a = document.getElementById("happy");
a.src = "about:blank";
r = document.createElement("a");
r.id="joy";
r.href="#";
r.innerText="JOY";
s = document.createElement("script");
s.src="fail.js";
a.contentWindow.document.body.appendChild(r);
a.contentWindow.document.body.appendChild(s);
答案 0 :(得分:0)
尝试将代码更改为:
// ...
var doc = a.contentWindow.document.open();
doc.write("<h3>Preview:</h3>" + scripttxt + "");
doc.close();
等等不,这也有类似的问题。
好吧,用“document.write”捣碎你的文件无论如何都是有点古怪的。这里的总体目标是什么?你不能用其他方式在文档中添加内容吗?
我想我理解你所得到的:有人会期望浏览器遵循正常的方式,加载脚本(并等待HTTP GET完成),运行脚本 - 这应该意味着脚本中的“写”调用仍然应该打开文档 - 然后返回。再说一次,对我来说这似乎有些冒险,因为它是我们正在讨论的单线程环境。
答案 1 :(得分:0)
您为什么使用document.write
?相反,请尝试附加脚本节点。
var d = document.getElementById("happy"),
s = document.createElement("script");
s.src= "http://asdf.com/asdf.js";
d.contentWindow.document.body.appendChild(s);
答案 2 :(得分:0)
我目前的解决方案似乎有效:
更改
a.contentWindow.document.close();
到
if (!isIE) {a.contentWindow.document.close();}
并在脚本上方添加此代码:
<script type='text/javascript'>
isIE = false;
</script>
<!--[if IE]>
<script type='text/javascript'>
isIE = true;
</script>
<![endif]-->
这个解决方案让我感到非常难过。