简体   繁体   English

动态复制<script> elements from external .html file

[英]Dynamycally copying <script> elements from external .html file

I have a (partial) html file containing this: 我有一个包含以下内容的(部分)html文件:

<div id="externalHTML">
External screen.
</div>
<script id="externalScript" type="text/javascript">
    function initScreen() { alert("Alerting from external script"); }
</script>

What I wanted is to load "externalScript" to some other html file "parent.html". 我想要的是将“ externalScript”加载到其他一些html文件“ parent.html”。 First, I tried this: 首先,我尝试了这个:

function loadScreen() {
            var xhr = new XMLHttpRequest();
            xhr.open('GET', "external.html", true);
            //Unimportant details omitted
                //Parse the response so that I can extract the script and ignore the div.
                var doc = new DOMParser().parseFromString(this.responseText, 'text/html');
                var extScript = doc.getElementById("externalScript");
                var extContainer = document.getElementById('extContainer');
                //Add the script to parent DOM
                screenContainer.appendChild(extScript);
            };
            xhr.send();
        }

This approach inserts the script element in parent DOM but the script is not executed. 此方法将脚本元素插入父DOM中,但脚本未执行。 I have found that by doing this: 我发现这样做:

...
//Create a copy of the script
var scr2 = document.createElement("script");
scr2.type = "text/javascript";
scr2.text = extScript.text;
//Add the script to parent DOM
screenContainer.appendChild(scr2);
...

The script is properly executed and I can call the "initScreen()" function. 该脚本已正确执行,我可以调用“ initScreen()”函数。 Can anyone explain to me what is happening here? 谁能向我解释这里发生了什么? Thank you. 谢谢。

Only a semi-educated answer, but I think this has to do with the document part of document.createElement . 只有一个半教育的答案,但我觉得这与做document的一部分document.createElement It's not so common, but a webpage can have multiple documents in it - like an iframe , an svg , or even a MathML document. 它并不常见,但是一个网页中可以包含多个文档-例如iframesvg甚至是MathML文档。 However, you can't just freely copy nodes between these documents; 但是,您不能只在这些文档之间自由复制节点; they have their own namespaces and attached behaviors. 它们具有自己的名称空间和附加的行为。 So, as you found in your fix, you need to create a matching <script> in your page document instead of using the node in the outside DOMParser . 因此,如在修补程序中所发现的,您需要在页面文档中创建匹配的<script> ,而不是使用外部DOMParser的节点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM