Skip to content Skip to sidebar Skip to footer

Dynamically Created Script Not Executing

I am appending a script tag, along with a bunch of other html, to my current document, retrieved from an ajax call. For some reason the script is not running //Response handling fu

Solution 1:

Check the following snippet and call the function as

var newEle = document.querySelector("#reportContainer");
exec_body_scripts(newEle);

Function

exec_body_scripts = function(body_el) {
  // Finds and executes scripts in a newly added element's body.// Needed since innerHTML does not run scripts.//// Argument body_el is an element in the dom.functionnodeName(elem, name) {
    return elem.nodeName && elem.nodeName.toUpperCase() ===
              name.toUpperCase();
  };

  functionevalScript(elem) {
    var data = (elem.text || elem.textContent || elem.innerHTML || "" ),
        head = document.getElementsByTagName("head")[0] ||
                  document.documentElement,
        script = document.createElement("script");

    script.type = "text/javascript";
    try {
      // doesn't work on ie...
      script.appendChild(document.createTextNode(data));      
    } catch(e) {
      // IE has funky script nodes
      script.text = data;
    }

    head.insertBefore(script, head.firstChild);
    head.removeChild(script);
  };

  // main section of functionvar scripts = [],
      script,
      children_nodes = body_el.childNodes,
      child,
      i;

  for (i = 0; children_nodes[i]; i++) {
    child = children_nodes[i];
    if (nodeName(child, "script" ) &&
      (!child.type || child.type.toLowerCase() === "text/javascript")) {
          scripts.push(child);
      }
  }

  for (i = 0; scripts[i]; i++) {
    script = scripts[i];
    if (script.parentNode) {script.parentNode.removeChild(script);}
    evalScript(scripts[i]);
  }
};

Solution 2:

It won't execute when you push it into the DOM in this way. Can you use jQuery? It will execute it:

$('#reportContainer').append('<scripttype="text/javascript">alert(123);</script>');

Solution 3:

What you get from ajax call is plain text or XML that can be inserted into DOM as HTML fragment, but all javascript code is explicitly forbidden for security reasons. There are plenty of choices to workaround this situation - from extracting part in the responseText and using eval method (not recommended, bad practice) to using of jQuery.load method.

Post a Comment for "Dynamically Created Script Not Executing"