Created
April 3, 2012 15:55
-
-
Save toddself/2293136 to your computer and use it in GitHub Desktop.
Asynchronous Template Loader
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
TemplateLoader = (function(){ | |
var template_cache = {}; | |
var template_path = '/tmpl'; | |
var loading_cache = {}; | |
var load_template = function(template, callback){ | |
var deferred = $.Deferred(); | |
if(_.isUndefined(template) || !_.isFunction(callback)){ | |
return false; | |
} | |
template = template.replace("#",""); | |
if(_.has(template_cache, template)){ | |
console.log('Template '+template+' is already cached locally'); | |
callback(template_cache[template]); | |
} else if(loading_cache.template){ | |
console.log('Template '+template+' is being loaded, so adding a callback to the deferred queue'); | |
deferred.done(callback); | |
} else { | |
console.log('Template '+template+' is not loading nor in cache, retreive from server'); | |
loading_cache[template] = true; | |
deferred.done(callback); | |
$.ajax({ | |
type: "GET", | |
url: join_paths(template_path, template), | |
success: function(resp){ | |
console.log('Template '+template+' has finished loading from the server'); | |
template_cache[template] = resp; | |
loading_cache[template] = false | |
deferred.resolve(resp); | |
} | |
}); | |
} | |
}; | |
var join_paths = function(){ | |
// strip off all / from start and end | |
return "/"+_.map(arguments, function(arg){ | |
if(_.isString(arg)){ | |
if(arg.slice(0, 1) === '/'){ | |
arg = arg.slice(1); | |
} | |
if(arg.slice(-1) === '/'){ | |
arg = arg.slice(0, -1); | |
} | |
} | |
return arg; | |
}).join('/'); | |
}; | |
return {load_template: load_template}; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment