Home > Web Front-end > JS Tutorial > How to Guarantee Inline Script Execution After Using innerHTML?

How to Guarantee Inline Script Execution After Using innerHTML?

Linda Hamilton
Release: 2024-12-31 08:21:10
Original
410 people have browsed it

How to Guarantee Inline Script Execution After Using innerHTML?

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';
}
Copy after login

Example Usage:

nodeScriptReplace(document.getElementsByTagName("body")[0]);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template