Apotheose
Apotheose

Reputation: 11

Function inside a script tag inserted via javascript remains undefined

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.

Upvotes: 1

Views: 1357

Answers (1)

Rick Hitchcock
Rick Hitchcock

Reputation: 35670

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>

Upvotes: 1

Related Questions