document.createElement(“脚本”)同步可以打电话给.js同步归档,然后立即使用它?<script type="text/javascript">
var head = document.getElementsByTagName('head').item(0);
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', 'http://mysite/my.js');
head.appendChild(script);
myFunction(); // Fails because it hasn't loaded from my.js yet.
window.onload = function() {
// Works most of the time but not all of the time.
// Especially if my.js injects another script that contains myFunction().
myFunction();
};</script>这很简单。在我的实现中,createElement在一个函数中。我考虑在函数中添加一些内容,以便在返回控件之前检查某个变量是否被实例化。但是,当包含来自另一个我无法控制的站点的js时,仍然存在着如何处理的问题。思想?编辑:我已经接受了最好的答案,因为它给出了一个很好的解释所发生的事情。但是如果有人对如何改进这个问题有任何建议的话,我对他们是开放的。这是我想做的事情的一个例子。// Include() is a custom function to import js.Include('my1.js');Include('my2.js');myFunc1('blarg');myFunc2('bleet');我只是不想太多地了解内部结构,只想说:“我希望使用这个模块,现在我将使用它中的一些代码。
3 回答

人到中年有点甜
TA贡献1895条经验 获得超7个赞
<script type="text/javascript"> document.write('<script type="text/javascript" src="other.js"></script>');</script><script type="text/javascript"> functionFromOther();</script>
<script type="text/javascript"> document.write('<script type="text/javascript" src="other.js"></script>'); window.onload = function() { functionFromOther(); };</script>
<script>
window.onload()
.
<script type="text/javascript"> document.write('<script type="text/javascript" src="other.js"></script>'); functionFromOther(); // Error</script>
document.write()
document.write()
.
添加回答
举报
0/150
提交
取消