0

I have some HTML structured as follows

<script>
function x()
{
 alert('works');
}
</script>

<table>
(...)
</table>

<script>
console.log('autoexec');
</script>

I am loading this HTML from a file in a DIV's innerHTML through an XMLHttpRequest.

Upon completion of the request, this is what I do

div.innerHTML = request.responseText;    
var scripts = div.getElementsByTagName("script");       
for(var i=0;i<scripts.length;i++) eval(scripts[i].text);     

The bottom script, containing code outside a function, gets executed. However the function x() in the top script isn't evaluated and remains unavailable.

What am I missing? Thanks

resle
  • 2,254
  • 4
  • 19
  • 37
  • you're probably missing that the function x is declared **but never executed**. add x(); somewhere inside your code, or auto invoke it. However, please, do NOT use eval() : http://stackoverflow.com/questions/86513/why-is-using-the-javascript-eval-function-a-bad-idea – briosheje Mar 10 '15 at 11:49
  • No, I know that x() wouldn't be executed. What I am saying is that it's not evaluated. It isn't available, not in the Window namespace nor elsewhere. – resle Mar 10 '15 at 11:53
  • Of course it is unavailable, because you're injecting it through an ajax request. By the time you're calling it the AJAX request cannot be completed yet, therefore you need to call that function in the window context only when the request has finished. – briosheje Mar 10 '15 at 11:54
  • FYI, you don't need to call the weird evals you're doing to the injected html. On adding new html containing ` – Kirill Slatin Mar 10 '15 at 11:58
  • No, I am doing the injection when the AJAX request has been completed. – resle Mar 10 '15 at 11:59

1 Answers1

0

Solved. Instead of eval(scripts[i].text) I now use document.head.appendChild(scripts[i]). This both correctly executes the code outside the function AND makes the function available for calling.

resle
  • 2,254
  • 4
  • 19
  • 37