What is the difference between handlebar.js and handlebar.runtime.js?

Solution 1:

Handlebars uses tags that look like {{this}} that can not be natively understood by the browser. In order for the browser to render these tags, they have to be compiled. Compilation can happen either before or after you load the page.

To speed things up, you can precompile your templates. More info at the handlebars site. If you do this, you only need to include the handlebars runtime script on your page. It's smaller than the full handlebars script because it doesn't need to worry about compiling templates. It assumes you have precompiled them.

When a template is compiled, it is converted into a function that, when called, will return real HTML wherein curly brace tags have been converted into values the browser understands.

For example, this...

<div class="entry">
  <h1>{{title}}</h1>
  <div class="body">
    {{body}}
  </div>
</div>

...will be converted into the following (as of June 2014) after being precompiled:

(function() {
  var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {};
templates['test.hbs'] = template({"compiler":[5,">= 2.0.0"],"main":function(depth0,helpers,partials,data) {
  var helper, functionType="function", escapeExpression=this.escapeExpression;
  return "<div class=\"entry\">\n  <h1>"
    + escapeExpression(((helper = helpers.title || (depth0 && depth0.title)),(typeof helper === functionType ? helper.call(depth0, {"name":"title","hash":{},"data":data}) : helper)))
    + "</h1>\n  <div class=\"body\">\n    "
    + escapeExpression(((helper = helpers.body || (depth0 && depth0.body)),(typeof helper === functionType ? helper.call(depth0, {"name":"body","hash":{},"data":data}) : helper)))
    + "\n  </div>\n</div>\n";
},"useData":true});
})();

The important takeaway here is that at some point, the handlebars template has to be converted into this function so that real HTML can be generated. The handlebars runtime script doesn't contain the compiler thus making it smaller. And by precompiling your templates, there will be one less heavy step the JavaScript has to go through before rendering the page.