有可能如果在每个脚本中都有可以测试的符号,或者每个脚本在加载完成后是否可以执行函数调用。
加载脚本很容易,我相信你知道:
var script = document.createElement('script');
script.src = /* ... the source path ... */;
document.body.appendChild(script);
(你会看到有人在 head 后面添加;没关系,body 很容易找到。)
但困难的部分是知道它何时被下载和执行。唯一真正做到这一点的方法是轮询以查看脚本定义的新全局符号是否已定义,或者让脚本在加载完成后主动回叫您(a'la JSONP)。
无论哪种方式,一旦您检测到符号或收到回调,您就可以继续加载下一个脚本。
这是一个基于查找全局符号(window 对象上的属性)的快速粗略草图:
// The scripts to load
var scriptList = {
scripts: [
{
file : 'some-script.js',
callback: function() {
// do some code here
},
symbol : "someSymbol",
timeout : 30000 // We know this one is slow, give it 30 seconds
},
{
file : 'another-script.js',
callback: function() {
// do some code here
},
symbol : "anotherSymbol"
},
// ...
]
};
// Triggering the load
loadScripts(scriptList);
// Library routines to do the load
function loadScripts(list)
{
var index, timeout;
// Start with the first one (loadNextScript starts with an increment)
index = -1;
loadNextScript();
// This function loads the next script in the list; if there are no
// more, it simply returns
function loadNextScript()
{
var script;
// Are there more?
++index;
if (index < list.length)
{
// Yes, append a `script` element
script = document.createElement('script');
script.src = list.file;
document.body.appendChild(script);
// Determine when to time out
timeout = new Date() + (list[index].timeout || 20000); // Time out in Xms, default 20 seconds
// Start polling
setTimeout(pollForScript, 0); // Async, but almost immediately (4-10ms on most browsers)
}
}
// This function polls to see if the current script has loaded yet by
// checking for a global symbol it defines.
function pollForScript()
{
var result;
// Has it been too long?
if (new Date() > timeout)
{
// Yes
result = "timeout";
}
else
{
// Has the symbol been defined?
if (typeof window[list[index].symbol] !== "undefined")
{
// Yes
result = "loaded";
}
else
{
// Nope, keep waiting
setTimeout(pollForScript, 250); // Check every quarter-second
}
}
// Did we get a result?
if (result)
{
// Yes, do the callback telling it of the result
try {
list[index].callback(result);
}
catch (e) {
}
// Load the next script
loadNextScript();
}
}
}