Hen*_*ryh 5 javascript events asynchronous
更新:
我有以下代码:
<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>
Run Code Online (Sandbox Code Playgroud)
在下载并执行所有必需的JS之前,如何防止代码执行?在上面的示例中,那些必需的文件是google-maps.js和jquery.js.
您可以onload为大多数浏览器使用script元素的事件,并使用回调参数:
编辑:当您以这种方式加载脚本时,您无法真正停止执行代码(并且在大多数情况下使同步Ajax请求成为一个坏主意).
但是你可以链接回调,所以如果你有一些依赖于Two.js和Three.js的代码,你可以链接加载动作,例如:
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...
});
});
Run Code Online (Sandbox Code Playgroud)
执行:
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);
}
Run Code Online (Sandbox Code Playgroud)
对于IE,onreadystatechange必须绑定事件.
| 归档时间: |
|
| 查看次数: |
813 次 |
| 最近记录: |