我如何能延缓运行一些JS code,直到我所有的异步JS文件下载? [英] How can I delay running some JS code until ALL of my asynchronous JS files downloaded?
问题描述
更新
我有以下的code:
<script type="text/javascript">
function addScript(url) {
var script = document.createElement('script');
script.src = url;
document.getElementsByTagName('head')[0].appendChild(script);
}
addScript('http://google.com/google-maps.js');
addScript('http://jquery.com/jquery.js');
...
// run code below this point once both google-maps.js & jquery.js has been downloaded and excuted
</script>
如何从执行,直到所有需要的JS prevent code已经被下载并执行?在上面我的例子中,这些必需的文件是谷歌,maps.js和的jquery.js。
How can I prevent code from executing until all required JS have been downloaded and executed? In my example above, those required files being google-maps.js and jquery.js.
推荐答案
您可以使用的onload脚本元素的
事件大多数浏览器,并使用一个回调参数:
You can use the onload
event of the script element for most browsers, and use a callback argument:
编辑:您不能真正阻止code的执行,当你以这种方式加载脚本(并使同步Ajax请求是一个坏主意,大部分的时间)
You can't really stop the execution of the code when you load scripts in this way (and making synchronous Ajax requests is a bad idea most of the times).
但你可以连锁回调,所以如果你有一些code,它取决于两者的 Two.js 的和的 three.js所的,你可以的链的加载操作,例如:
But you can chain callbacks, so if you have some code that depends on both, Two.js and Three.js, you can chain the loading actions, for example:
loadScript('http://example.com/Two.js', function () {
// Two.js is already loaded here, get Three.js...
loadScript('http://example.com/Three.js', function () {
// Both, Two.js and Three.js loaded...
// you can place dependent code here...
});
});
实施
function loadScript(url, callback) {
var head = document.getElementsByTagName("head")[0],
script = document.createElement("script"),
done = false;
script.src = url;
// Attach event handlers for all browsers
script.onload = script.onreadystatechange = function(){
if ( !done && (!this.readyState || // IE stuff...
this.readyState == "loaded" || this.readyState == "complete") ) {
done = true;
callback(); // execute callback function
// Prevent memory leaks in IE
script.onload = script.onreadystatechange = null;
head.removeChild( script );
}
};
head.appendChild(script);
}
有关IE浏览器中,<一个href=\"http://msdn.microsoft.com/en-us/library/ms536957%28VS.85%29.aspx\"><$c$c>onreadystatechange$c$c>事件已被约束。
For IE, the onreadystatechange
event has to be bound.
这篇关于我如何能延缓运行一些JS code,直到我所有的异步JS文件下载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!