Search code examples
javascriptappendchilddynamic-script-loading

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?


Solution

  • 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.