开发者

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?


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.


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜