sprugman
sprugman

Reputation: 19831

Javascripts added via appendChild don't seem to run

I've got a javascript file being added dynamically to a page. If I use document.write, it works fine:

<html>
<head></head>
<body>
    <script type="text/javascript">
          var src = 'myDynamicScript.js';
          document.write('<scr' + 'ipt type="text/javascript" src="' + src + '"></scr' + 'ipt>');
    </script>
</body>
</html>

However, if I use appendChild, as outlined in this answer, the script gets downloaded, but never runs:

<html>
<head></head>
<body>
    <script type="text/javascript">
          var src = 'myDynamicScript.js';
          var script = document.createElement("script");
          script.type  = "text/javascript";
          script.src   = src;
          document.body.appendChild(script);
    </script>
</body>
</html>

I've got a simple example set-up here (write) and here (append). Should I expect it to run, or is that the known behavior? If it should, why isn't it?

Upvotes: 3

Views: 3168

Answers (2)

Kent Brewster
Kent Brewster

Reputation: 2520

Your examples work for me in Safari. Here are some questions:

What browsers are you testing? (Guessing you're having trouble on IE.) Are you trying this from a server and not just dragging index.html into your browser?
What else is running on the page that might be blocking myDynamicServer.js?
Has something hijacked window.onload?
Have you tried appending myDynamicServer.js to document.getElementsByTagName('BODY')[0] and not document.body?

Upvotes: 0

Matti Virkkunen
Matti Virkkunen

Reputation: 65156

Your script is running all right, you just can't document.write from it. Use an alert or something to test it and avoid using document.write altogether.

Upvotes: 3

Related Questions