var wrap = document.createElement("div"); wrap.innerHTML = '<script type="text/javascript" src="'+scriptUrl+'"></script>'; var wrapscript = wrap.childNodes[0]; document.body.appendChild(wrapscript)
正文确实插入了脚本元素,但js资源没有加载,甚至没有http请求…
谁能告诉我为什么~~
问题出在Zeptojs的$方法上
$('<script type="text/javascript" src="'+scriptUrl+'"></script>').appendTo($("bdoy"))
解决方法
如规范(8.4 Parsing HTML fragments和8.2.3.5 Other parsing state flags)中所述,引用:
当使用innerHTML时,浏览器会
Create a new Document node,and mark it as being an HTML document.
If there is a context element,and the Document of the context element is in quirks mode,then let the Document be in quirks mode.
Otherwise,if there is a context element,and the Document of the
context element is in limited-quirks mode,then let the Document be in
limited-quirks mode. Otherwise,leave the Document in no-quirks mode.Create a new HTML parser,and associate it with the just created Document node.
…
并且在解析< script>时内
The scripting flag is set to “enabled” if scripting was enabled for
the Document with which the parser is associated when the parser was
created,and “disabled” otherwise.The scripting flag can be enabled even when the parser was originally
created for the HTML fragment parsing algorithm,even though script
elements don’t execute in that case.
所以只要你用innerHTML注入它就不会被执行.
并且使用innerHTML将阻止< script>永久执行创建的元素.
如规范(4.3.1 The script element,)中所述:
Changing the src,type,charset,async,and defer attributes dynamically has no direct effect; these attribute are only used at specific times described below.
总结下面描述的是,它只在解析< script>时解析src属性.到文档(无论哪个,包括使用innerHTML时创建的temporary one.)
因此,只要您想要将脚本注入文档并使其执行,就必须使用script = document.createElement(‘script’).
设置其属性,如src和type,可能是内部的内容(通过使用script.appendChild(document.createTextNode(content))),然后将其附加到document.body.