1

My problem is that when I create a script tag trough javascript

    var script = document.createElement('script');      
    script.setAttribute('type', 'text/javascript');
    document.getElementById("fastexe").appendChild (script);

(the div parent of the script is before this script), and I insert a function in it like so

    script.innerHTML = "function in_my_script(){ \n";
    script.innerHTML += "alert('test'); \n }";

when I try to call my function (function_in_my_script) through the console or even like this:

    script.innerHTML += "\n function_in_my_script();";

I get a function not defined error, for apparently no reason. I tried with different function names, nothing inside of the function and different alerts in the function but nothing changed the result.

I don't understand why the function stays undefined. Thanks for your help.

3
  • 1
    What browser are you doing this in? Afaik, some have problems with innerHTML on script elements Commented Apr 2, 2016 at 11:06
  • 1
    You should try filling the script element before appending it to the DOM. Afaik that's the only time when it will be evaluated. Commented Apr 2, 2016 at 11:06
  • Your function is called in_my_script, not function_in_my_script. If this is just example code, please edit your question. Commented Apr 2, 2016 at 11:10

1 Answer 1

1

Each time you append a string to the SCRIPT element's innerHTML, the browser tries to run the element. This leads to a syntax error when the SCRIPT is simply function in_my_script(){.

Instead, build the script's contents in a variable, and then add it to script.innerHTML all at once:

var script = document.createElement('script'),
    s;

script.setAttribute('type', 'text/javascript');
document.getElementById("fastexe").appendChild(script);

s = "function in_my_script(){ \n";
s += "alert('test'); \n }";
s += "\n in_my_script();";

script.innerHTML= s;
<div id="fastexe"></div>

Sign up to request clarification or add additional context in comments.

1 Comment

Working ! Thank you really much, never tought it could be interpreted that way !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.