JavaScript在DIV中动态加载脚本 [英] JavaScript load script dynamically inside a DIV
问题描述
我已经动态创建了一个DIV,我希望它包含一个JavaScript链接,该链接将在其上输出内容.JavaScript链接源是绝对的.显然,这是行不通的:
I have created a DIV dynamically and I want it to contain a JavaScript link, that will output something on it. The JavaScript link source is absolute. Obviously, this doesn't work:
var div = document.createElement('div');
div.id = 'mydiv';
div.innerHTML = "<script type='text/javascript' " +
"src='http://mydomain.com/myscript.js'></script>";
document.body.appendChild(div);
所以我尝试了这个
var script = document.createElement('script')
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', 'http://mydomain.com/myscript.js');
var div = document.createElement('div');
div.id = 'mydiv';
div.appendChild(script);
document.body.appendChild(div);
在我的脚本文件中,我有一个简单的 alert('Testing ...');
代码.问题是它不起作用.脚本包含项在div中键入(当我在Chrome中检查DIV时可以看到它),但是它不起作用.我没有看到正在测试..." 消息.我想念什么或做错什么?谢谢!
In my script file I have a simple alert('Testing...');
code.
The problem is that it doesn't work. The script inclusion is typed inside the div (I see it when I inspect the DIV in Chrome), but it doesn't work. I don't see the 'Testing...' message.
What am I missing or doing wrong? Thanks!
推荐答案
按照我的理解,您的代码不会等到DOM准备就绪.
The way i understand it, your code does not wait till the DOM is ready.
建议使用jquery的就绪,这将确保传递给它的脚本仅在DOM准备就绪
It is advised to use jquery's ready which will ensure that the script passed to it runs only after the DOM is ready
希望这会有所帮助
这篇关于JavaScript在DIV中动态加载脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!