Asynchronous files loading with jQuery deferred with callback

FilesLoader.js


// Main `TemplateManager` object
// The Template Loader. Used to asynchronously load files 

window.FilesLoader = {

  files: {},

  load: (function(views, callback) {

    var deferreds = [], tplPath;

    var defaults = {
      path: opt.tpl.options.path,
      ext: opt.tpl.options.ext
    };


    $.each(views, function(index, view) {
        var self = this;
        //Convert to string
        view = "" + view;
        //tpl file path
        tplPath = "" + defaults.path + view + defaults.ext;

        deferreds.push( $.ajax({
          url: tplPath,
          success: function(tplString) {
            self.files[view] = {
              tplString: tplString,
              compiled: Handlebars.compile(tplString)
            };
          },
          dataType: 'html',
          cache: true,
        }) );

    });
    $.when.apply($, deferreds).done(callback);
  }).bind(this);

};

Usage


var tplsToLoad = [
  'tpl/menu-section',
  'tpl/header',
  'tpl/footer'
];

window.FilesLoader.load(tplsToLoad,
function () {
  //Do what you want to do after all templates loaded
});
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s