I\'ve got a script that inserts some content into an element using innerHTML
.
The content could for example be:
Here's a shorter, more efficient script that also works for scripts with the src
property:
function insertAndExecute(id, text) {
document.getElementById(id).innerHTML = text;
var scripts = Array.prototype.slice.call(document.getElementById(id).getElementsByTagName("script"));
for (var i = 0; i < scripts.length; i++) {
if (scripts[i].src != "") {
var tag = document.createElement("script");
tag.src = scripts[i].src;
document.getElementsByTagName("head")[0].appendChild(tag);
}
else {
eval(scripts[i].innerHTML);
}
}
}
Note: whilst eval
may cause a security vulnerability if not used properly, it is much faster than creating a script tag on the fly.