Skip to content

Instantly share code, notes, and snippets.

@ThomasBurleson
Forked from cowboy/shmemplates.js
Created November 17, 2011 01:54
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 ThomasBurleson/1372142 to your computer and use it in GitHub Desktop.
Save ThomasBurleson/1372142 to your computer and use it in GitHub Desktop.
Promises: template caching w/ $.getScript()
// shmemplates. req: needs to work x-domain and be fully cacheable
Bocoup.utils.template = (function($) {
// Request a template from the server. Returns a Deferred object.
function fn(key) {
return $.Deferred(function(dfd) {
if (key in fn.cache) {
dfd.resolve(fn.cache[key]);
} else {
$.getScript(fn.url + key, function() {
dfd.resolve(fn.cache[key]);
});
}
});
}
// The cache.
fn.cache = {};
// The URL.
fn.url = 'http://server.com/templates/';
// The server-generated JavaScript calls this function.
fn.handle = function(key, tmpl) {
fn.cache[key] = Handlebars.compile(tmpl);
};
// Expose the interface.
return fn;
}(jQuery));
// You do this in your code:
var tmpl = Bocoup.utils.template('header');
$.when(tmpl, otherAjaxRequest).then(function(tmpl, ajaxResponse) {
// something with tmpl and ajaxResponse
});
tmpl.done(function(tmpl) {
// something with tmpl
});
// FWIW, the server sends back this:
Bocoup.utils.template.handle('header', '<h1>{{header}}</h1>');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment