的eval()不执行的外部(SRC = ...)脚本 [英] eval() doesn't execute external (src=...) scripts
问题描述
我用的eval()
来执行所有<脚本>
的div的总重写后的标签(其code通过加载一个 XMLHtt prequest
)
I'm using eval()
to execute all <script>
tags after total rewrite of a div (whose code is loaded via an XMLHttpRequest
):
var arr = document.getElementById('idOfDIV').getElementsByTagName('script');
for (var n = 0; n < arr.length; n++){
try {
eval(arr[n].innerHTML);
} catch(err) {
console.log(err);
}
}
它非常适用内嵌的脚本,但像脚本没有影响:
It works well for inline-scripts, but has no effect on scripts like:
<script src="/path/to/externalScript.js"></script>
怎么来的?我可以强制的浏览器加载,并执行外部脚本?
How come? Can I "force" the browser to load and execute also the external scripts?
请注意:正如我所提到的,问题也许显得奇怪,关于一个事实,即的eval()
执行字符串的JavaScript。我需要做的,是强制浏览器加载载粘贴DOM外部脚本,并执行它们。
NOTE: As I noted, the question may seems "strange", regarding the fact that eval()
executes a string as javascript. What I need to do, is the force the browser to load external scripts contained in "pasted" DOM, and execute them.
推荐答案
下面一件事你可以做:
var html = "Some html with a script <script>alert('test');</script>";
var frag = parsePartialHtml(html);
fixScriptsSoTheyAreExecuted(frag);
document.body.appendChild(frag);
function fixScriptsSoTheyAreExecuted(el) {
var scripts = el.querySelectorAll('script'),
script, fixedScript, i, len;
for (i = 0, len = scripts.length; i < len; i++) {
script = scripts[i];
fixedScript = document.createElement('script');
fixedScript.type = script.type;
if (script.innerHTML) fixedScript.innerHTML = script.innerHTML;
else fixedScript.src = script.src;
fixedScript.async = false;
script.parentNode.replaceChild(fixedScript, script);
}
}
function parsePartialHtml(html) {
var doc = new DOMParser().parseFromString(html, 'text/html'),
frag = document.createDocumentFragment(),
childNodes = doc.body.childNodes;
while (childNodes.length) frag.appendChild(childNodes[0]);
return frag;
}
这篇关于的eval()不执行的外部(SRC = ...)脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!