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?

7

1 Answer 1

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.

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

2 Comments

So I take it that appending ( appendChild ) it is different from doing a .innerHTML write for some reason?
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("<script>alert('x');</script>") as well as $("head").append("<script>alert('x');</script>")

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.