BlackFire27
BlackFire27

Reputation: 1550

Injecting javascript dynamically and using it

I also create a javascript file dynamically that uses those variables:

      function callbackF(data){
          console.log(data.script);

          document.getElementsByTagName('head')[0].innerHTML=data.script;

        var script = document.createElement("script");
    script.setAttribute("src", "http://widget.example.com/sprk.1.0.2.js");
    script.setAttribute("type", "text/javascript");
    script.setAttribute("id", "grazit_script");
    document.getElementsByTagName('head')[0].appendChild(script);
        }

This is what i get in my head:

This is what is printed to the console log:

<script type='text/javascript'>var dbnwid=16476; var dbnpid=23369; var dbnwebid=19720; var dbnlayout=21; var dbncolor='#000000'; var dbntitlefontsize='14'; var dbnbgcolortype=1; var dbnheader='You might enjoy reading:'; var dbnremindercolor=2; var dbn_protocol = (('https:' == document.location.protocol) ? 'https://' : 'http://'); </script> 

and then the script:

<script src="http://widget.example.com/sprk.1.0.2.js" type="text/javascript" id="grazit_script"></script>

The second script should get the variables that are in the second script..but it doesnt..then it complains about why it doesnt get those variables

UPDATE: Both of those ways below didnt work for me:

  eval(data.script);
           var ss= new Function(data.script)();

Upvotes: 0

Views: 113

Answers (1)

Guffa
Guffa

Reputation: 700402

Because scripts run when they are loaded. Adding a script tag using innerHTML doesn't run the code inside the tag.

Upvotes: 2

Related Questions