javascript – 使用div的innerHTML创建脚本标记不起作用

前端之家收集整理的这篇文章主要介绍了javascript – 使用div的innerHTML创建脚本标记不起作用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
这里是js代码
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 fragments8.2.3.5 Other parsing state flags)中所述,引用:

当使用innerHTML时,浏览器会

  1. Create a new Document node,and mark it as being an HTML document.

  2. 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.

  3. 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.

原文链接:https://www.f2er.com/js/156072.html

猜你在找的JavaScript相关文章