3

Possible Duplicate:
Executing <script> elements inserted with .innerHTML
Dynamically Inserting <script> tags into HTML on Page Load

What I mean is that if I do .innerHTML write that contains

<script type="text/javascript" src="source.js"></script>

or

<script type="text/javascript"> // embedded code here </script>

The embedded code does not run and neither does the linked to code. It is "dead".

Is there a way to manually trigger it?

Community
  • 1
  • 1
CS_2013
  • 1,078
  • 3
  • 12
  • 22
  • What about errors in javascript console? – zerkms May 14 '12 at 20:44
  • Duplicate of [Dynamically Inserting – Phrogz May 14 '12 at 20:44
  • How are these tags being added? – Rocket Hazmat May 14 '12 at 20:44
  • @Phrogz, Quentin, this is 3 different answers to one problem..this is not a duplicate. – CS_2013 May 14 '12 at 20:48
  • @Rocket - via .innerHTML write...I get the data from and ajax response. – CS_2013 May 14 '12 at 20:48
  • http://24ways.org/2005/have-your-dom-and-script-it-too... this way is a hack that uses a downloaded images onload property, which apparently fires when written to the .innerHTML, to run some script – CS_2013 May 14 '12 at 20:51
  • Got to go with it...as is about 1 line of code instead of 35 for the other "solutions"...just use like a 1 byte image on your server. – CS_2013 May 14 '12 at 20:53

1 Answers1

3

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.

kritzikratzi
  • 16,501
  • 1
  • 25
  • 38
  • So I take it that appending ( appendChild ) it is different from doing a .innerHTML write for some reason? – CS_2013 May 14 '12 at 20:55
  • i think it's about adding to the head, not how to add it ... if you open up the javascript console on a page with jquery and try you can see that both these work: ```$("head").html("")``` as well as $("head").append("") – kritzikratzi May 14 '12 at 21:05