更新:
我有以下代码:
<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 下载并执行之前阻止代码执行?在我上面的例子中,那些必需的文件是 google-maps.js 和 jquery.js。
最佳答案
对于大多数浏览器,您可以使用 script 元素的 onload
事件,并使用回调参数:
编辑:当您以这种方式加载脚本时,您无法真正停止代码的执行(大多数时候进行同步 Ajax 请求并不是一个好主意)。
但是你可以链接回调,所以如果你有一些代码同时依赖于 Two.js 和 Three.js,你可以链接 加载 Action ,例如:
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,onreadystatechange
必须绑定(bind)事件。
关于javascript - 我怎样才能延迟运行一些 JS 代码,直到我的所有异步 JS 文件都下载完毕?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2800323/