Skip to content

Instantly share code, notes, and snippets.

@jonkemp
Last active June 8, 2016 08:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonkemp/32657022c28da0b8f9b0 to your computer and use it in GitHub Desktop.
Save jonkemp/32657022c28da0b8f9b0 to your computer and use it in GitHub Desktop.
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