Skip to content

Instantly share code, notes, and snippets.

@nleush
Last active December 10, 2018 15:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nleush/51e8aee92a7b0a71e6a5d1ae3f2bea36 to your computer and use it in GitHub Desktop.
Save nleush/51e8aee92a7b0a71e6a5d1ae3f2bea36 to your computer and use it in GitHub Desktop.
native javascript insert <script> (code or link) in DOM
function exec_body_scripts(body_el) {
function nodeName(elem, name) {
return elem.nodeName && elem.nodeName.toUpperCase() ===
name.toUpperCase();
}
function evalScript(elem) {
var data = (elem.text || elem.textContent || elem.innerHTML || "" ),
script = document.createElement("script");
if (elem.src) {
script.src = elem.src;
}
script.type = "text/javascript";
try {
// doesn't work on ie...
script.appendChild(document.createTextNode(data));
} catch(e) {
// IE has funky script nodes
script.text = data;
}
body_el.appendChild(script);
}
// main section of function
var scripts = [],
script,
children_nodes = body_el.childNodes,
child,
i;
for (i = 0; children_nodes[i]; i++) {
child = children_nodes[i];
if (nodeName(child, "script" ) &&
(!child.type || child.type.toLowerCase() === "text/javascript" || child.type.toLowerCase() === "application/javascript")) {
scripts.push(child);
} else {
exec_body_scripts(child);
}
}
for (i = 0; scripts[i]; i++) {
script = scripts[i];
if (script.parentNode) {script.parentNode.removeChild(script);}
evalScript(scripts[i]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment