是否可以.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>
Run Code Online (Sandbox Code Playgroud)
这是简化的.在我的实现中,createElement的东西在一个函数中.我想在函数中添加一些东西,可以在返回控件之前检查某个变量是否被实例化.但是,当我从另一个我无法控制的网站中包含js时,仍然存在一个问题.
思考?
编辑:
我现在已经接受了最好的答案,因为它为正在发生的事情提供了一个很好的解释.但如果有人对如何改进这一点有任何建议我会向他们开放.这是我想做的一个例子.
// Include() is a custom function to import js.
Include('my1.js');
Include('my2.js');
myFunc1('blarg');
myFunc2('bleet');
Run Code Online (Sandbox Code Playgroud)
我只是想从不必知道的内部太多,只能够说,保持"我希望用这个模块,现在我会使用一些代码吧."