Home >Web Front-end >JS Tutorial >Why Doesn't innerHTML Execute Scripts, and How Can I Fix It?

Why Doesn't innerHTML Execute Scripts, and How Can I Fix It?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-25 08:40:10160browse

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

. However, it's often observed that while the script content appears in the page's DOM, it remains unexecuted in browsers like Firefox and Chrome.

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!

Statement:
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