Josep 是对的,如果它在您使用 alert() 时有效,那是因为那会阻塞执行,这为 ajax 调用和回调的执行提供了时间。
但是,与其对代码进行那么多重构,不如将对$.liteAccordion() 的调用移至回调中。例如:
$(document).ready(function () {
$('head').append("<script id='templateHolder' type='text/template'></script");
$('#templateHolder').load('templates/template.html', function () {
var scripts = ['js/liteaccordion.jquery.js', 'js/mustache.js']; //add as many script as required here
for (var i = 0; i < scripts.length; i++) {
$.getScript(scripts[i], function () {
$.getJSON('json/data.json', function (data) {
var template = $('#templateHolder').html();
var info = Mustache.to_html(template, data);
$('.jsoncontent').html(info);
$('.jsoncontent').liteAccordion(); //move here
}); //eof .getJSON
}); //eof .getScript()
} //eof for()
}); //eof load()
}); //eof ready()
但是,我对您选择使用$.getScript() 有点好奇——因为您的for() 循环中的代码实际上并不需要那样运行;为每个脚本获取一次 JSON 是没有意义的;最好先获取每个脚本,然后获取 JSON 一次.. 例如..
$(document).ready(function () {
$('head').append("<script id='templateHolder' type='text/template'></script");
$('#templateHolder').load('templates/template.html', function () {
var scripts = ['js/liteaccordion.jquery.js', 'js/mustache.js']; //add as many script as required here
for (var i = 0; i < scripts.length; i++) {
$.getScript(scripts[i], function () {
//just get the script; this callback doesn't need to do anything really
}); //eof .getScript()
} //eof for()
/* we're out of the for() loop now, so this will only make the call
once; however - all our scripts are loaded so it will work */
$.getJSON('json/data.json', function (data) {
var template = $('#templateHolder').html();
var info = Mustache.to_html(template, data);
$('.jsoncontent').html(info);
$('.jsoncontent').liteAccordion(); //move here
}); //eof .getJSON
}); //eof load()
}); //eof ready()
此解决方案再次将 $.liteAcordion() 调用放在回调中,因此它将在 Mustache.js 被调用后执行。
值得记住的是,AJAX 有时是异步的,因为如果你不充分利用回调函数等,它可能会让人头疼。
但是,正如@Josep 在下面的 cmets 中指出的那样,您仍然面临$.getScript() 尚未完成执行的风险;对于您在数组中包含的更多脚本,这将是一个问题。
考虑到这一点,稍微重构一下并从for() 循环中调用$.getJSON() 可能会更好;但确保它绝对是 last 迭代。 (编辑:我看到 Jesop 实际上有一个相同的解决方案 - 我知道我们大多数人都在这里获得积分,但如果你要接受答案 - 接受他的答案,他先到了那里;) )
$(document).ready(function () {
$('head').append("<script id='templateHolder' type='text/template'></script");
$('#templateHolder').load('templates/template.html', function () {
var scripts = ['js/liteaccordion.jquery.js', 'js/mustache.js']; //add as many script as required here
for (var i = 0; i < scripts.length; i++) {
$.getScript(scripts[i], function () {
if( i == (scripts.length -1) )
$.getJSON('json/data.json', function (data) {
var template = $('#templateHolder').html();
var info = Mustache.to_html(template, data);
$('.jsoncontent').html(info);
$('.jsoncontent').liteAccordion(); //move here
}); //eof .getJSON
}); //eof .getScript()
} //eof for()
}); //eof load()
}); //eof ready()