使用jQuery聪明下载多个模板文件?

时间:2017-04-24 16:40:29

标签: javascript jquery

我想下载并缓存多个小胡子模板,我知道这样做的唯一真正方法是通过jQuery.ajax() - 方法下载它们。

所以我直截了当的preload-init代码看起来有点......丑陋!

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);
  });
}

1 个答案:

答案 0 :(得分:2)

你没有指定你正在使用哪个版本的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

上有很多很好的例子