我想下载并缓存多个 Mustache-templates,我知道的唯一真正的方法是通过 jQuery.ajax()
方法下载它们。
所以我简单的预加载初始化代码看起来有点......丑陋!
function getAllTemplatesUglyAndNotPerformant() {
//this is no longer valid, stays just for reference; look at the bottom for the solution
//easy - preload the template and execute it to the data
$.ajax({
url: 'fragments/employee.mustache',
success: function (employeeTpl) {
//uh-oh async process-handling forces me into digging this deeper
$.ajax({
url: 'fragments/employee_day.mustache',
success: function (dayTpl) {
//third level - now i am puzzled already
$.ajax({
url: 'fragments/employee_day_regular.mustache',
success: function (protodayTplRegular) {
//monologue: am i doing this right?
$.ajax({
url: 'fragments/employee_day_deleted.mustache',
success: function (protodayTplDeleted) {
//most probably not
var cachedTemplates = {
employee: employeeTpl,
day: dayTpl,
protoday: {
regular: protodayTplRegular,
deleted: protodayTplDeleted
}
};
//shoot, i also cannot return cachedTemplates, better bury my init-method in this!
init(cachedTemplates);
}
});
}
});
}
});
}
});
}
//initializes downloading and parsing data to what will be seen
function init(cachedTemplates) {
//get the data
$.ajax(
url: '_get_data.php',
success: function (data) {
if (data.success) {
$.each(data.employees, function (iEmployee, vEmployee) {
//this goes through a custom rendering for an employee and his sub-nodes stored in arrays (all rendered in Mustache)
var employee = parseEmployee(vEmployee);
var html_employee = employee.render(cachedTemplates);
$('#data-position').append(html_employee);
});
}
//ignore what may else happen for now
}
)
}
有没有更好的方法在JS中下载多个文件进行缓存?
编辑: 我对 getAllTemplates() 的重写现在看起来更像这样,并且最终“更容易理解”并且对于下一个接触“Peters Legacy”的人来说性能更好:
function getAllTemplates() {
$.when(
$.get('fragments/employee.mustache'),
$.get('fragments/employee_day.mustache'),
$.get('fragments/employee_day_regular.mustache'),
$.get('fragments/employee_day_deleted.mustache')
)
.done(function (employeeTpl, acquisitionTpl, protodayTplRegular, protodayTplDeleted) {
var cachedTemplates = {
employee: employeeTpl[0],
acquisition: acquisitionTpl[0],
protoday: {
regular: protodayTplRegular[0],
deleted: protodayTplDeleted[0]
}
};
init(cachedTemplates);
});
}
最佳答案
您没有指定您正在使用哪个版本的 jQuery,因此这里假设您使用的是最新版本;
您可以使用 jQuery 1.5+ 中的 $.when()
。
$.when()
允许您捆绑(本质上)一堆异步方法(在本例中为 ajax)并等待所有方法完成。在您的示例中,您将触发一个请求,等待响应,然后触发另一个请求。使用 $.when()
;如果您的连接允许它们可以同时触发,在您的示例中可以节省大量时间!
类似于:
$.when(
$.ajax( "fragments/employee.mustache" ),
$.ajax( "fragments/employee_day.mustache" ),
$.ajax( "..." )
)
.done(function( employeeRes, dayRes ) {
// the first item in array should be the data
var employeeTpl = employeeRes[0];
var dayTpl = dayRes [0];
// ...
});
jQuery Website 有很多很好的例子。
关于javascript - 使用 jQuery 聪明地下载多个模板文件吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43593562/