Last active
August 29, 2015 14:06
-
-
Save detj/64f41d02ce67821189aa to your computer and use it in GitHub Desktop.
async template loading with requests caching
This file contains hidden or 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
| /** | |
| * Asynchronously fetches a template & caches it internally | |
| * | |
| * If a request for a template hasn't completed yet and another | |
| * request arrives, then instead of queuing the request resolve | |
| * the deffered with the previously cached request | |
| */ | |
| function fetchTemplate(path) { | |
| /** | |
| * Template Cache | |
| * | |
| * Stores the actual template content | |
| */ | |
| var JST = Backbone.Layout.cache('template-cache'); | |
| /** | |
| * Template Request Cache | |
| * | |
| * Keeps a tab on ongoing requests | |
| */ | |
| var reqcache = Backbone.Layout.cache('template-req-queue'); | |
| // return the template content if already in cache | |
| if (JST[path]) { | |
| return JST[path]; | |
| } | |
| // make this function async | |
| var done = this.async(); | |
| if (!reqcache[path]) { | |
| // if this is a new request then | |
| // do the request | |
| var req = $.get(path, null, null, 'text'); | |
| // and add in request cache | |
| reqcache[path] = req; | |
| // run a function request completes | |
| req.done(complete); | |
| } else { | |
| // if we have already seen this request | |
| // then wait for the ongoing request to | |
| // complete and resolve the latter requests | |
| // with former's response | |
| reqcache[path].done(complete); | |
| } | |
| function complete(contents) { | |
| // compile the template & cache it | |
| done(JST[path] = _.template(contents)); | |
| if (path in reqcache){ | |
| delete reqcache[path]; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment