Home >Web Front-end >JS Tutorial >Why Doesn't innerHTML Execute Scripts, and How Can I Fix It?
Scripting with innerHTML: A Workaround for Browser Execution Limitations
In an attempt to dynamically load scripts into a web page, developers may utilize the innerHTML property of HTML elements, such as
To address this issue, a recursive method has been devised that effectively replaces non-executable scripts with executable counterparts. This method, outlined below, ensures faithful execution upon insertion through innerHTML:
function nodeScriptReplace(node) { if (nodeScriptIs(node)) { node.parentNode.replaceChild(nodeScriptClone(node), node); } else { var i = -1, children = node.childNodes; while (++i < children.length) { nodeScriptReplace(children[i]); } } return node; } function nodeScriptClone(node) { var script = document.createElement("script"); script.text = node.innerHTML; var i = -1, attrs = node.attributes, attr; while (++i < attrs.length) { script.setAttribute((attr = attrs[i]).name, attr.value); } return script; } function nodeScriptIs(node) { return node.tagName === 'SCRIPT'; }
Usage: By invoking the nodeScriptReplace() method on the body element of the document, all non-executable scripts will be replaced with their executable counterparts, enabling seamless script execution:
nodeScriptReplace(document.getElementsByTagName("body")[0]);
This technique effectively circumvents the browser limitations regarding script execution when inserted via innerHTML, allowing developers to dynamically load and execute scripts as desired.
The above is the detailed content of Why Doesn't innerHTML Execute Scripts, and How Can I Fix It?. For more information, please follow other related articles on the PHP Chinese website!