是否可以同步调用.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');
我只是不想过多地了解内部结构,并且可以说,“我希望使用这个模块,现在我将使用其中的一些代码。”