Last active
December 10, 2018 15:30
-
-
Save nleush/51e8aee92a7b0a71e6a5d1ae3f2bea36 to your computer and use it in GitHub Desktop.
native javascript insert <script> (code or link) in DOM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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