document.createElement('script')...添加两个脚本与一个回调 [英] document.createElement('script')... adding two scripts with one callback
问题描述
我需要添加原型,然后添加scriptaculous并在加载时得到回调。我目前正在加载原型:
I need to add prototype and then add scriptaculous and get a callback when they are both done loading. I am currently loading prototype like so:
var script = document.createElement("script");
script.src = "http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js";
script.onload = script.onreadystatechange = callback;
document.body.appendChild( script );
我可以通过链接回调来做到这一点,但这似乎是糟糕的练习(我不想一个愚蠢的20个回调方法链,当我需要加载更多的脚本)。想法?
I could do this by chaining the callbacks, but that seems like poor practice ( I don't want a silly chain of 20 callback methods when I need to load more scripts). Ideas?
推荐答案
我建议您使用一些小型装载机,为您链接并做些事情。例如像这样一个:
I propose you to use some small loader which will chain and do stuff for you. For example like this one:
function loadScripts(array,callback){
var loader = function(src,handler){
var script = document.createElement("script");
script.src = src;
script.onload = script.onreadystatechange = function(){
script.onreadystatechange = script.onload = null;
handler();
}
var head = document.getElementsByTagName("head")[0];
(head || document.body).appendChild( script );
};
(function run(){
if(array.length!=0){
loader(array.shift(), run);
}else{
callback && callback();
}
})();
}
此脚本可帮助您构建脚本标记,并在所有文件被加载。调用很简单:
This script should help you to build the script tags and call your callback when all files are loaded. Invoke is pretty easy:
loadScripts([
"http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js",
"http://ajax.googleapis.com/ajax/libs/prototype/1.6.1.0/prototype.js"
],function(){
alert('All things are loaded');
});
希望这将有助于
这篇关于document.createElement('script')...添加两个脚本与一个回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!