Skip to content

Instantly share code, notes, and snippets.

@mohandere
Created June 21, 2017 12:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mohandere/6161f6995d53ee8bdc6784987a56bd0a to your computer and use it in GitHub Desktop.
Save mohandere/6161f6995d53ee8bdc6784987a56bd0a to your computer and use it in GitHub Desktop.
Asynchronous files loading with jquery deferred with callback
//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
});
// 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);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment