0

Is this possible?

I inserted a simple test snippet like this

<script type="text/javascript">//<![CDATA[ 
document.write('foo');
//]]></script> 

but it does nothing. ( W3 schools suggest the use of CDATA here, but this did not help ).

To reiterate this snippet was written into the .innerHTML property of the body tag.

I've seen some mentions of eval() on google but not too sure if this is relevant or good practice?

Wrapping the code in eval like they do here at W3 has no effect.

1 Answer 1

2

Javascript is only executed on first read, not when it is dynamically inserted as such. You would have to use something like the eval() function to execute the content of the actual script. You could also use DOM functions like getObjectsByTagName() to grab the script tag, and get its contents from there.

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

3 Comments

And yes, eval() is generally not good practice but there can be times when it is appropriate. Many programmers use such functions to patch over a larger design flaw. I can't comment on your usage given the lack of context of the actual calling script.
I strongly recommend not using .innerHTML to run all of your JS. If you have no scripts running, and no event handlers with which to fire scripts, you don't have any way to call scripts you have inserted with .innerHTML. You may want to look into jQuery and its .ready() function (see api.jquery.com/ready). Why are you trying to emulate an onload event? I assume you are somehow unable to use existing onload events or other handlers? Edit - this was in response to an OP comment which I no longer see
It is executed when you dynamically add it using the actual object and not .innerHTML

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.