There was some concern about my previous solution, that it loads templates synchronously and serially. An application should have templates inlined before it goes to production anyway.
Fair point though, there is a better way.
Better Definition
Firstly; Marionette.js can transparently lazy-load and cache DOM-stored templates;
//What I had been doing var MyView1 = Marionette.ItemView.extend({ template: _.template( $("#template_myview1").html() ) }); //What I should have been doing var MyView2 = Marionette.ItemView.extend({ template: "#template_myview2" });
The difference between the two is significant.
- MyView1 will access the DOM as soon as the class is defined, and build the template immediately.
- MyView2 will access the DOM only when a MyView2 instance is constructed, but only builds the template once.
This means the templates are only built at the time they are first used. The template blocks don’t need to be accessible at the time the classes are defined. The app only needs to build the template functions the first time they are used.
Using the MyView2 style will give much faster start-up times for larger applications.
(Marionette.TemplateCache can be used stand-alone, or you can fairly easily create your own caching DOM template loader)
Better Loading
Now, the template blocks won’t be referenced until they are used. We can load them asynchronously now, but we still don’t want to start the app until the templates have been fetched. $.ready(…) won’t wait for the templates, but there’s a fairly easy workaround;
//A list of promises that need to resolve before starting var loaded = []; //Load all templates var $templates = $('script[type="text/template"]'); $templates.each(function() { var src = $(this).attr("src"); if (src) { loaded.push( //Wait for the template to load $.ajax(src, {context:this}). done(function(data) { $(this).html(data); }) ); } }); //Wait for the DOM to be ready loaded.push($.ready); //Initialise after everything is loaded $.when.apply($,loaded).done(function() { //Start application });
There! With that in place;
- Templates are loaded into script blocks as you’d expect, asynchronously and in parallel.
- The application starts after the DOM and the templates are loaded.
- For production, the templates are inlined. Without any code changes, the application will transparently start as soon as $.ready is completed.