3

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?

Community
  • 1
  • 1
sprugman
  • 17,781
  • 31
  • 105
  • 160

2 Answers2

3

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.

Matti Virkkunen
  • 58,926
  • 7
  • 111
  • 152
  • Why can't I use document.write (apart from it being "evil")? I mean why is it forbidden in this particular situation? – sprugman Sep 29 '11 at 21:43
  • It's not forbidden, but it will happen after the original document (that is, your main page) has already been **closed**. When you do a subsequent "write()" operation, the original page will be thrown away. – Pointy Sep 29 '11 at 21:47
  • Actually, @Pointy, it seems to be the opposite -- as far as I can tell, the document.write in the appendChild-ed script either never happens or gets overwritten by the main page somehow. If I put it inside a setTimeout, then I can get it to overwrite my main page. – sprugman Sep 30 '11 at 22:01
0

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?

Kent Brewster
  • 2,410
  • 2
  • 22
  • 27