Add replaceScriptNodes function

This commit is contained in:
Ian Henderson 2016-05-17 11:05:59 -07:00
parent 7c392f071d
commit 1673579d32

View file

@ -1176,9 +1176,41 @@
$document.createRange().createContextualFragment(data))
} catch (e) {
parentElement.insertAdjacentHTML("beforeend", data)
replaceScriptNodes(parentElement)
}
}
// Replace script tags inside given DOM element with executable ones.
// Will also check children recursively and replace any found script
// tags in same manner.
function replaceScriptNodes(node) {
if (node.tagName === "SCRIPT") {
node.parentNode.replaceChild(buildExecutableNode(node), node)
} else {
var children = node.childNodes
if (children && children.length) {
for (var i = 0; i < children.length; i++) {
replaceScriptNodes(children[i])
}
}
}
return node
}
// Replace script element with one whose contents are executable.
function buildExecutableNode(node){
var scriptEl = document.createElement("script")
var attrs = node.attributes
for (var i = 0; i < attrs.length; i++) {
scriptEl.setAttribute(attrs[i].name, attrs[i].value)
}
scriptEl.text = node.innerHTML
return scriptEl
}
function injectHTML(parentElement, index, data) {
var nextSibling = parentElement.childNodes[index]
if (nextSibling) {