Techniques for Executing Inline Scripts Using innerHTML
Inserting scripts into a web page using innerHTML has its limitations. While the script may appear in the DOM, it often fails to execute automatically. To address this issue and enable script execution upon insertion, certain methods can be employed.
Method: Recursively Replace Scripts
This approach involves replacing each inline script element with an executable counterpart. The following code snippet demonstrates the implementation:
function nodeScriptReplace(node) { if (nodeScriptIs(node) === true) { 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'; }
Example Usage:
nodeScriptReplace(document.getElementsByTagName("body")[0]);
This method recursively traverses the DOM tree, identifying and replacing inline script elements with executable ones, ensuring that scripts execute as expected.
The above is the detailed content of How to Guarantee Inline Script Execution After Using innerHTML?. For more information, please follow other related articles on the PHP Chinese website!