[英]Dynamically insert an HTML string into the HEAD of a Document
I need to insert an HTML string into the <head>
tag of the current document DOM, one way is: you create a div element, fill its innerHTML, copy over item-by-item into your <head>
element. 我需要在当前文档DOM的
<head>
标记中插入一个HTML字符串,一种方法是:创建一个div元素,填充其innerHTML,逐项复制到<head>
元素中。 But these methods do not work in IE/Opera for reasons given below, though in FF3 both the below methods work perfectly, and the browser processes the added STYLE/SCRIPT elements. 但是这些方法没有在IE / Opera一起使用下面给出的理由,但在FF3下面的方法都很好地工作,并且浏览器处理添加样式/ SCRIPT元素。
Is there any other way you can insert a string directly into <head>
and have those items processed? 有没有其他方法可以直接将字符串插入
<head>
并处理这些项目?
(Why they fail in IE/Opera) (为什么他们在IE / Opera中失败)
Method 1 - Fails because innerHTML cannot parse/ignores META, STYLE, SCRIPT elements within the string 方法1 - 失败,因为innerHTML无法解析/忽略字符串中的META,STYLE,SCRIPT元素
insertHtml = function(parentElem,htmlStr){
var frag = document.createDocumentFragment();
var temp = document.createElement('div');
temp.innerHTML = htmlStr;
// at this point, temp.childNodes.length=0
while (temp.firstChild) {
frag.appendChild(temp.firstChild);
}
// use native DOM methods to insert the fragment
parentElem.insertBefore(frag, parentElem.childNodes[0]);
}
Method 2 - Fails because added STYLE/SCRIPT elements do not get processed by the browser 方法2 - 失败,因为浏览器不会处理添加的STYLE / SCRIPT元素
document.getElementsByTagName("head")[0].innerHTML = htmlStr
// although this populates the <head> tag successfully
Here's a stupid hack that solves the problem. 这是一个解决问题的愚蠢黑客。 Prepend a non-empty string tag (node.nodeType === 3) to the htmlStr and everything will work:
将非空字符串标记(node.nodeType === 3)添加到htmlStr,一切都会正常工作:
var insertHtml = function(parentElem, htmlStr){
var frag = document.createDocumentFragment();
var temp = document.createElement('div');
temp.innerHTML = "hack" + htmlStr;
while (temp.firstChild) {
if (temp.firstChild.nodeType === 1) {
// add only element nodes
frag.appendChild(temp.firstChild);
} else {
// remove the hack string
temp.removeChild(temp.firstChild);
}
}
parentElem.insertBefore(frag, parentElem.childNodes[0]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.