是否可以同步调用.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');
我只想避免对内部结构了解太多,只想说:“我希望使用这个模块,现在我将使用其中的一些代码。”
https://stackoverflow.com/questions/3248384
复制相似问题