I\'m using eval()
to execute all tags after total rewrite of a div (whose code is loaded via an
XMLHttpRequest
):
Here's one thing you could do:
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;
}
This tag :
<script src="/path/to/externalScript.js"></script>
has empty innerHTML, so you cant eval the content
What you could do is to check if the script has an src
attribute, and add a script tag in the head with this src :
function addHeadScript = function(src){
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.type = "text/javascript";
script.src = src;
head.appendChild(script);
}
...
for (var n = 0; n < arr.length; n++){
if (arr[n].src != ""){
addHeadScript(arr[n].src);
}
else {
// Evaluate the script `innerHTML` OR
// Create a script tag in the head and set it's content equal to arr[n].innerHTML
}
}