Executing ≪Script≫ Elements Inserted With .Innerhtml

Executing script elements inserted with .innerHTML

The OP's script doesn't work in IE 7. With help from SO, here's a script that does:

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.

function nodeName(elem, name) {
return elem.nodeName && elem.nodeName.toUpperCase() ===
name.toUpperCase();
};

function evalScript(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 function
var 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]);
}
};

Can scripts be inserted with innerHTML?

You have to use eval() to execute any script code that you've inserted as DOM text.

MooTools will do this for you automatically, and I'm sure jQuery would as well (depending on the version. jQuery version 1.6+ uses eval). This saves a lot of hassle of parsing out <script> tags and escaping your content, as well as a bunch of other "gotchas".

Generally if you're going to eval() it yourself, you want to create/send the script code without any HTML markup such as <script>, as these will not eval() properly.

How can I run script that was added to the page with innerHTML?

you need to add the javascript to the head tag,
i.e

var head = document.getElementsByTagName("head")[0];         
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'http://www.somedomain.com/somescript.js';
head.appendChild(newScript);

(this is a quite common thing, but i copied the code from here: http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS )


on a side note:
if you use jQuery you will be tempted to write the following:

<script>
[....]
$( "head" ).append( "<script src='myScript.js'></script>" );
[....]
</script>

note that this doesn't work because the javascript parser will see the first </script> and stop parsing right there.

setting innerHTML with a script inside

It looks like that your <script> tag is being added as you expect, but the code within it is not being executed. The same failure happens if you try using document.head (or any other DOM element, it seems). For whatever reason (possibly standards compliance, possible security), inline code inside of <script> blocks that are added via .innerHTML simply doesn't run.

However, I do have working code that produces similar functionality:

var script = document.createElement('script');
script[(script.innerText===undefined?"textContent":"innerText")] = 'alert(1);';
document.documentElement.appendChild(script);

Here, you add the <script> block with documentElement.appendChild and use textContent or innerText to set the content of the <script>.

Executing script injected by innerHTML after AJAX call

JavaScript inserted as DOM text will not execute. However, you can use the dynamic script pattern to accomplish your goal. The basic idea is to move the script that you want to execute into an external file and create a script tag when you get your Ajax response. You then set the src attribute of your script tag and voila, it loads and executes the external script.

This other StackOverflow post may also be helpful to you: Can scripts be inserted with innerHTML?.

Insert script to a div via innerHTML working but not loading

There is no innerText in an external script. Also innerHTML does not render scripts

You likely want to do this:

var myDiv = document.getElementById("mydiv");

var oldWrite = document.write, html=[];

document.write = function(str) {

html.push(str);

}

var script = document.createElement("script");

script.src="https://gist.github.com/raselahmed7/e233c308d5bf354c9d174f80a30c6b6a.js"

document.getElementsByTagName("head")[0].appendChild(script)

setTimeout(function() { myDiv.innerHTML=html.join("\n") },1000)
<div id="mydiv"></div>


Related Topics



Leave a reply



Submit