为什么我不能在 IE 中将包含 script 标签的字符串添加到innerHTML
我正在尝试执行以下操作(我正在使用原型库):
var div = document.createElement('div');
div.innerHTML = '<script src="somescript.js"></script>';
$('banner').insert(div);
在 IE 中,在我在第二行中设置属性后,div.innerHTML 属性始终等于“”。
该代码段位于一个函数内,该函数在外部供应商脚本中重写 document.write() ,因此这就是为什么我这样做,而不是创建脚本元素并将其直接附加到 div 元素。
任何帮助将不胜感激,这让我白发了!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这件事也让我陷入了困境。 事实证明,IE 不允许直接通过innerHTML 插入JS,除非包含'defer' 属性(参见下面的第二个链接)。 此属性是 IE 所独有的,并且显然允许 IE 推迟任何 JS 的执行,直到加载其他标记之后。 不过,警告...如果您包含两个脚本标记(就像我所做的那样),则无法保证哪一个将首先执行,因为脚本似乎是异步加载的。 只有当您的脚本相互依赖时(就像我的脚本一样),这才应该成为一个问题。
还有一个额外的警告......您必须在插入脚本的同时插入非脚本标记。 我无法自行插入脚本标签,无论是否带有“defer”属性。 最后,脚本标记必须放置在插入所有其他非脚本标记之后。 否则,脚本标记将从插入的 HTML 中删除。
以下是一些参考:
MS innerHTML 参考:
http ://msdn.microsoft.com/en-us/library/ms533897%28v=vs.85%29.aspx
MS 延迟属性参考:
http://msdn.microsoft.com/en-us/library/ms533719%28v=vs.85%29。 aspx
通过代码插入脚本的示例(是的,它确实有效):
http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/insertScript_2.htm
我的测试代码:
This one had me stymied for a bit as well. It turns out that IE does not allow the insertion of JS directly via innerHTML unless you include the 'defer' property (see the second link below). This property is unique to IE and apparently allows IE to defer execution of any JS until after the other markup has been loaded. A warning, though...if you include two script tags (as I did), there is no guarantee which one will execute first, as the scripts appear to be loaded asynchronously. This should only be a problem if your scripts are dependent on one another (as mine were).
There is an additional caveat as well...you must insert non-script markup at the same time that you insert the script. I was unable to insert the script tags by themselves, with or without the 'defer' property. Finally, the script tags must be placed after all other non-script markup being inserted. Otherwise, the script tags are stripped out of the inserted HTML.
Here are a few references:
MS innerHTML Reference:
http://msdn.microsoft.com/en-us/library/ms533897%28v=vs.85%29.aspx
MS Defer Property Reference:
http://msdn.microsoft.com/en-us/library/ms533719%28v=vs.85%29.aspx
Example of Script Insert via code (yes, it actually does work):
http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/insertScript_2.htm
My Test Code:
您的脚本标签可能正在设法独立解释。 尝试:
Your script tag is probably managing to be interpreted independently. Try:
你可以尝试做这样的事情:
或者做
You could try to do something like this instead:
or do
您需要对
使用转义字符,
请参阅为什么在 javascript '<\/script>' 中转义 /?
you need to use escape char for the
</script>
see why escaping / in javascript '<\/script>'?
您是否尝试过添加内联 JS 而不是加载 .js 文件? 我过去曾这样做过,而且对我来说效果很好。 不确定这是否仍然适用于最新的浏览器/安全问题。
HTH。
Have you tried to add inline JS instead of loading a .js file? I've done this in the past and it worked fine for me. Not sure if that would still work with the lastest browsers / security missery.
HTH.