Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Load and cache external templates with jQuery and Underscore. Returns a promise. Useful for JavaScript MVC frameworks, such as Backbone.js.
/* global $, _ */
var TemplateManager = {};
(function () {
'use strict';
var cache = {};
TemplateManager.template = function (path) {
var deferred = new $.Deferred(),
resolvePromise = function (template) {
deferred.resolveWith( null, [ _.template( template ) ] );
};
if (cache[path]) {
resolvePromise( cache[path] );
} else {
$.get(path, function(data) {
cache[path] = data;
resolvePromise( data );
});
}
return deferred.promise();
};
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment