JavaScript Performance: Pre-Compiling And Caching HTML Templates

If you’re using HTML templates with a JavaScript application, you need to be caching the template’s raw text and/or pre-compiled version of the template. All of this spawned from a fun thread of discussion on a StackOverflow question.

DOM Selection Is Expensive

If you didn’t know this already, DOM selection is expensive. So expensive, in fact, that it should be avoided whenever possible. Of course avoiding it entirely is not likely as we need DOM selection to handle events, update the UI, and more. There’s a huge performance impact on having to constantly select a

Screen Shot 2012 03 28 at 9 35 57 PM

If you’re storing templates in a script tag, don’t access that DOM element more than once. After all, you’re not expecting the contents of the template to change. Only the data that is rendered in to the template changes.

Simple Template Caching

The easiest way of storing a template is to use the DOM selector as a key, and the template contents as a value. Check for the existence of that key on an object, and if it exists use that. If it doesn’t exist, load it:

Pre-Compile Templates

One of the commenters in the thread of discussion liked the test I put together but thought it could be done better, still. He updated it to show cached vs non-cached and pre-compiled vs non-pre-compiled templates.

Screen Shot 2012 03 28 at 10 02 37 PM

Clearly, pre-compiling your templates is important. So let’s update our TemplateCache to pre-compile the templates for us (assuming we’re using underscore.js):

Template Cache Built In To Backbone.Marionette

Of course you saw this part coming, right? I’ve got a much more robust version of the above template caching already available in Backbone.Marionette. It defaults to using underscore.js as it’s template engine, but that’s really easy to change. See the documentation for some examples on how to do that.

But even if you’re not using Backbone or Backbone.Marionette, you need to take advantage of the performance improvements that your application will see, by only selecting something from the DOM once, and by pre-compiling and caching any templates that you’re using.

Composite Views: Tree Structures, Tables, And More