Created
June 21, 2017 12:21
-
-
Save mohandere/6161f6995d53ee8bdc6784987a56bd0a to your computer and use it in GitHub Desktop.
Asynchronous files loading with jquery deferred with callback
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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 | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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