I have started using Backbone.js but with handlebars templates (like in Ember.js) that I parse through Underscore.js. Anyway, to cut a long story short – I did not want to have a bunch of flat script tags with HTML in the document body on page load so I thought of a way to lazyload and bring the templates from an external repository.
The result is Asset.templates – written in the style of MooTools more’s Asset.images/javascript or whatever. The idea is: it uses Request.HTML to fetch the template file; it then injects it as a script tag into the document.head; it sets the correct type (text/x-handlebars in the example but it’s an option) and a property that lets you use a selector engine to reference and load it (data-template-name in the example, but it can be anything, including id – if you like).
It loads the files asynchronously and firess onProgress and onComplete events – as well as onFailure. If any template is missing and onFailure fires, it won’t fire the onComplete so you can recover early.
Loading a template a second time will NOT inject a new script tag but will update the existing template instead.
Here’s a gist with the code and an example case:
Full gist here: https://gist.github.com/1768949
GitHub flavoured markdown enabled.